# Constraints & Defaults

> Let the database enforce your rules with NOT NULL, UNIQUE, CHECK and keys, fill gaps with defaults, and avoid the CHECK and NULL trap.

Subject: SQL | Lesson 36 of 44 | 7 min read
Interactive lesson: https://codewithanimation.in/sql/constraints-and-defaults
Previous: [CREATE, ALTER & DROP TABLE](https://codewithanimation.in/sql/create-alter-drop-tables.md) | Next: [Normalization](https://codewithanimation.in/sql/normalization.md)

## Rules the database enforces for you

A **constraint** is a rule attached to a table. Every row that is inserted or changed must obey it, or the statement is rejected. The main ones are `NOT NULL`, `UNIQUE`, `PRIMARY KEY`, `FOREIGN KEY` and `CHECK`.

A **default** is the value a column takes when an `INSERT` leaves it out. If you declare no default, the default is `NULL`.

## Rules in one place

If the rule "a price is above zero" lives only in your program, any other program, script or person can break it. A constraint protects the data no matter who writes it.

## A table with rules

```sql
CREATE TABLE items (
  id integer PRIMARY KEY,
  name text NOT NULL UNIQUE,
  price integer CHECK (price > 0),
  qty integer DEFAULT 1,
  created time DEFAULT CURRENT_TIMESTAMP,
  total integer GENERATED ALWAYS AS (price * qty)
);
```

`INSERT INTO items (name, price) VALUES ('Pen', 5)` works: id comes from a sequence, qty becomes 1, created gets the time of this insert, and total is worked out from price and qty. A default that is an expression, such as `CURRENT_TIMESTAMP`, is evaluated each time a row is inserted, not once when the table is created.

A repeated name breaks `UNIQUE`. A price of 0 breaks the `CHECK`. A **generated column** such as `total` is always computed from other columns, so you cannot write to it (you may write `DEFAULT`). In PostgreSQL 18 a generated column is virtual by default: it is worked out when you read it, and `STORED` keeps it on disk.

## Common mistake: CHECK lets NULL through

A `CHECK` passes when its test is true **or unknown**. `price > 0` is unknown when price is `NULL`, so `CHECK (price > 0)` still accepts a NULL price. If NULL must be rejected, add `NOT NULL` as well. The manual points this out directly.

`UNIQUE` also treats NULLs as different from each other, so a UNIQUE column can hold many NULLs. `NULLS NOT DISTINCT` changes that.

When a row breaks several rules, PostgreSQL reports one: NOT NULL is checked first, then CHECK, then UNIQUE and PRIMARY KEY. A rejected row can still use up a serial number.

A foreign key says what happens when the parent row is deleted: `NO ACTION` or `RESTRICT` refuse, `CASCADE` deletes the children, `SET NULL` or `SET DEFAULT` clears the link.

## Tip: Name the rule, and put the rule in the table

Add `NOT NULL` to every column that must have a value, and `CHECK` for value ranges. If you leave a constraint unnamed, PostgreSQL chooses a name such as `items_price_check`, but a name you choose, with `CONSTRAINT positive_price CHECK (...)`, makes error messages easier to read.

## Try it: Break the rules on purpose

Insert a good row, then try a repeated name, a price of 0, and a NULL price. Switch to NOT NULL and CHECK and try the NULL price again.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/sql/constraints-and-defaults

## Check yourself

### Question 1

A column is declared `price integer CHECK (price > 0)`. Can you insert a row with `price` set to NULL?

- A. Yes, because the CHECK is unknown for NULL, and unknown passes
- B. No, because NULL is not greater than 0
- C. Only if the column has a default

Correct answer: A

The manual says a check constraint is satisfied if the expression is true or null. Add NOT NULL to stop NULLs.

- Why not B: NULL > 0 is unknown, not false. A CHECK only rejects a false result.
- Why not C: The default has nothing to do with it. The CHECK itself lets NULL through.

### Question 2

A column has `DEFAULT CURRENT_TIMESTAMP`. When is the default time worked out?

- A. Each time a row is inserted without a value for it
- B. Once, when the table is created
- C. When the row is first read

Correct answer: A

Every insert that leaves the column out gets the time of that insert.

- Why not B: An expression default is evaluated whenever the default is inserted, not when the table is created.
- Why not C: Reading never changes a stored default.

### Question 3

`total` is declared `GENERATED ALWAYS AS (price * qty)`. What does `INSERT ... (total) VALUES (99)` do?

- A. It is rejected, because a generated column cannot be written to
- B. It stores 99
- C. It stores 99 until the next update

Correct answer: A

A generated column is always computed from other columns, so a value cannot be given for it.

- Why not B: A generated column is always computed from other columns. You may only write DEFAULT to it.
- Why not C: There is no way to override it. It is always price times qty.

## Remember this

- A constraint is a rule the database enforces on every insert and update: NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK.
- A column with no declared default has NULL as its default. An expression default is evaluated at each insert.
- A CHECK passes when its test is true or NULL, so add NOT NULL to reject NULLs.
- A generated column is computed from other columns and cannot be written to.
