FresherTechnicalSQL
Which constraints can a column have in SQL?
Try answering first
Model answer
Constraints are rules the database enforces on every write, so bad data is rejected no matter which application sends it.
- NOT NULL: the column must have a value.
- UNIQUE: no two rows share the same value. NULLs are allowed, and most engines treat them as distinct.
- PRIMARY KEY: identifies a row, and combines NOT NULL with UNIQUE. A table has one.
- FOREIGN KEY: the value must exist in a referenced table, with rules such as
ON DELETE CASCADE. - CHECK: a condition each row must satisfy. MySQL enforces it from 8.0.16.
- DEFAULT: a value used when none is given. Strictly it is not a restriction, but it is declared the same way.
CREATE TABLE products (
id BIGINT PRIMARY KEY,
sku VARCHAR(40) NOT NULL UNIQUE,
price NUMERIC(10,2) NOT NULL CHECK (price >= 0),
status VARCHAR(20) NOT NULL DEFAULT 'draft',
brand_id BIGINT REFERENCES brands (id)
);
Constraints keep integrity in one place, while checks in application code can be bypassed by a script or another service.
Put rules that must never be broken into constraints, not only into code.
Key points
- NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK, DEFAULT
- PRIMARY KEY is NOT NULL plus UNIQUE
- FOREIGN KEY enforces references between tables
- Constraints protect data from every client
Likely follow-ups
- Can a UNIQUE column hold more than one NULL?
Common mistakes
- Relying only on application validation instead of constraints
- Thinking UNIQUE rejects multiple NULLs in every engine