Junior — Middle
How can restrictions be imposed on a database table?
sobes.tech AI
Answer from AI
Constraints in a database table help ensure data integrity. Main types of constraints:
- PRIMARY KEY — a unique identifier for a row, does not allow NULL.
- FOREIGN KEY — a reference to a key in another table, ensures referential integrity.
- UNIQUE — guarantees the uniqueness of values in a column or set of columns.
- NOT NULL — prohibits NULL values in a column.
- CHECK — a condition that values in a column must satisfy.
Example of creating a table with constraints:
CREATE TABLE users (
id INT PRIMARY KEY,
email VARCHAR(255) UNIQUE NOT NULL,
age INT CHECK (age >= 18),
role_id INT,
FOREIGN KEY (role_id) REFERENCES roles(id)
);
In Java, when working with a database through ORM (e.g., Hibernate), constraints can be set using annotations such as @NotNull, @UniqueConstraint, etc.