Junior — Middle
What other constraints are reasonable to use in a database besides PRIMARY KEY, UNIQUE, NOT NULL, and CHECK?
sobes.tech AI
Answer from AI
Besides PRIMARY KEY, UNIQUE, NOT NULL, and CHECK, databases often use the following constraints:
- FOREIGN KEY — ensures referential integrity between tables, guaranteeing that the value in the column exists in the related table.
- DEFAULT — sets a default value for a column if no value is specified during data insertion.
- INDEX (although not exactly a constraint) — speeds up searches on the column but does not affect data integrity.
- EXCLUSION CONSTRAINT (in some DBMSs, such as PostgreSQL) — allows setting exclusion conditions for rows.
Example of using FOREIGN KEY:
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);
This guarantees that you cannot insert a customer_id into orders that does not exist in the customers table.