Junior — Middle
Could you explain what is meant by constraints in SQL and how they are applied?
sobes.tech AI
Answer from AI
Constraints in SQL are rules that are applied to table columns to ensure data integrity and correctness. They help prevent errors and inconsistencies.
Main types of constraints:
- PRIMARY KEY — a unique identifier for a row, cannot be NULL.
- FOREIGN KEY — maintains referential integrity between tables.
- UNIQUE — guarantees the uniqueness of values in a column.
- NOT NULL — prohibits storing empty values.
- CHECK — sets a condition that data 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)
);
Here, we ensure that each user has a unique id and email, and the age is at least 18.