Junior — Middle
What database constraints do you know and use in SQL?
sobes.tech AI
Answer from AI
In SQL, there are various constraints that ensure data integrity:
- PRIMARY KEY — a unique identifier for a record, cannot be NULL.
- FOREIGN KEY — a reference to a key from another table, ensures a relationship between tables.
- UNIQUE — guarantees the uniqueness of values in a column.
- NOT NULL — prohibits NULL values in a column.
- CHECK — sets a condition that values in a column must meet.
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)
);
These constraints help prevent errors and maintain data correctness.