SQL CONSTRAINTS are declarative rules that the database engine evaluates whenever data is inserted, updated, or deleted. They guarantee that each row and relationship in a table stays valid. Constraints can be defined inline at the column level or separately at the table level. The most common types are:- PRIMARY KEY – identifies each row uniquely and implies NOT NULL and UNIQUE.- FOREIGN KEY – links a column or group of columns to the PRIMARY KEY or UNIQUE key of another table, enforcing referential integrity.- UNIQUE – prevents duplicate values within the constrained column set.- CHECK – validates that each value satisfies a Boolean expression.- NOT NULL – disallows NULL values in a column.- DEFAULT – supplies a value when none is provided.Constraints are validated on every write operation. Some dialects allow deferring validation until COMMIT, temporarily disabling a constraint, or creating it as NOT VALID to validate later. Naming constraints (CONSTRAINT my_name ...) simplifies maintenance and error handling. Poorly designed or missing constraints can lead to orphaned rows, duplicate records, and hard-to-trace bugs.Because constraints execute automatically inside the database engine, they are faster, safer, and easier to audit than manual checks in application code.
SQL-92
Use ALTER TABLE ADD CONSTRAINT. Example:```ALTER TABLE employeesADD CONSTRAINT uq_email UNIQUE (email);```
The database aborts the statement, rolls back that statement’s changes, and returns an error describing the violated constraint.
No, but naming them (CONSTRAINT constraint_name ...) is best practice because it eases troubleshooting and future ALTER or DROP operations.
Yes. You can declare any number of CHECK clauses, each evaluating its own Boolean condition. Every condition must be true for a row to be accepted.