Data types, keys & constraints
Enforce data integrity with primary keys, foreign keys, CHECK and UNIQUE.
By Invicly Tech, , in SQL & PostgreSQL. About 11 minutes to read.
In short
Good types and constraints make the database reject bad data instead of hoping every app gets it right. Keys identify rows, foreign keys protect relationships, and CHECK and UNIQUE enforce business rules.
Explained simply
Every column has a data type that decides what it can hold: whole numbers, exact decimals, text, dates, true or false. Picking the right type gives you free checking (you cannot store 'banana' in a date) and makes storage and sorting correct.
Constraints are rules the database enforces on every insert and update, no matter which app, script or person sends the data. A primary key says each row is unique. A foreign key says a referenced row must exist. CHECK says a condition must be true. UNIQUE says no duplicates.
Why not just validate in the app? Because there is never only one app. There are admin scripts, data imports, a second service, and a tired developer in psql at midnight. The database is the last line of defence, and it never forgets to check.
When a rule is broken, Postgres rejects the statement with a clear error, such as "violates check constraint". That is good: a loud failure today is much cheaper than quietly wrong data found months later.
Press Play on a diagram to walk through it one step at a time.
- PRIMARY KEY
- Unique and NOT NULL
- Identity or natural key
- FOREIGN KEY
- ON DELETE RESTRICT
- ON DELETE CASCADE
- ON DELETE SET NULL
- UNIQUE
- No duplicate emails
- CHECK
- price >= 0
- end_at > start_at
- NOT NULL
- Value is required
- 1Type input
Each value must parse as its column type
- 2NOT NULL
Required columns must have a value
- 3CHECK
Each row condition must not be false
- 4UNIQUE / PK
Unique indexes reject duplicates
- 5FOREIGN KEY
Referenced parent row must exist
- 6Row stored
Any failure aborts the whole statement
In depth
Choosing data types in PostgreSQL
Numbers: integer is 4 bytes and tops out at about 2.1 billion; bigint is 8 bytes and is the safe default for ids. Use numeric(p,s) for money and anything that must be exact, never real or double precision, which are approximate.
Text: in Postgres, text and varchar(n) perform the same. varchar(n) only adds a length check, so use text and add a CHECK if a limit is a real business rule.
Time: timestamptz stores an exact moment (internally in UTC) and converts to the session time zone for display. Use it for events. Use date for calendar days like a birthday, and plain timestamp only for local wall-clock times with no zone.
Others: boolean for yes or no, uuid for ids generated outside the database, jsonb for flexible documents, and inet for IP addresses.
- Ids: bigint identity (or uuid)
- Money: numeric(12,2)
- Moments: timestamptz; calendar days: date
- Strings: text, plus CHECK for real limits
- Flexible attributes: jsonb
Surrogate or natural keys, identity or UUID
A natural key is a real-world value that is already unique, like an ISBN or a country code. A surrogate key is a made-up id with no meaning. Natural keys feel tidy, but real-world values change (people change emails) and are sometimes reused, and every foreign key must change with them. Most teams use a surrogate primary key and add a UNIQUE constraint on the natural key.
For surrogate ids, bigint GENERATED ALWAYS AS IDENTITY is the modern standard SQL way; it replaces the older serial type. UUIDs are useful when ids are created by clients or across many databases, or when you do not want ids to be guessable. gen_random_uuid() (UUID version 4) is built in, and PostgreSQL 18 adds uuidv7(), whose time-ordered values keep B-tree indexes compact.
- 8 bytes, fast to compare
- Ordered, compact indexes
- Guessable in URLs
- Needs the database to create it
- 16 bytes
- Created anywhere, no clash
- Not guessable
- v7 is time-ordered, v4 is random
- Already meaningful (ISBN)
- No extra column
- Can change or be reused
- Changes ripple to every FK
Foreign keys and their ON DELETE rules
A foreign key checks that every value in the child column exists in the parent. What happens when someone deletes a parent row is your choice. NO ACTION (the default) and RESTRICT both reject the delete if children exist; the difference is that NO ACTION can be checked at the end of the transaction if the constraint is declared DEFERRABLE. CASCADE deletes the children too, which is right for parts that cannot live alone, like order lines. SET NULL keeps the child but clears the link, which suits optional links like a post whose author account was removed. SET DEFAULT puts the column's default value instead.
The same choices exist for ON UPDATE, but surrogate keys never change, so it rarely matters.
Two practical notes: index the child column yourself, and remember that CASCADE on a big table can delete millions of rows in one statement.
- NO ACTION / RESTRICT
- Delete is rejected
- Safest default
- CASCADE
- Child rows are deleted too
- Use for owned parts
- SET NULL
- Child FK becomes NULL
- Column must be nullable
- SET DEFAULT
- Child FK gets its default
- Default row must exist
UNIQUE, CHECK and the rules beyond them
UNIQUE creates a unique index behind the scenes. By default NULLs count as different, so many rows can have a NULL email. Since PostgreSQL 15 you can write UNIQUE NULLS NOT DISTINCT to allow only one.
A unique index can also be partial or use an expression. CREATE UNIQUE INDEX ON users (lower(email)) blocks 'Ann@x.com' when 'ann@x.com' exists. Adding WHERE deleted_at IS NULL lets a soft-deleted user's email be reused.
CHECK takes any boolean expression on the same row: price >= 0, status IN ('new','paid','shipped'), end_at > start_at. It cannot look at other rows or tables.
For "no two bookings of the same room may overlap", use an exclusion constraint with a range column: EXCLUDE USING gist (room_id WITH =, during WITH &&), which needs the btree_gist extension for the equality part.
- UNIQUE NULLS NOT DISTINCT (PG 15+)
- Case-insensitive unique: index on lower(email)
- CHECK sees only the current row
- EXCLUDE USING gist for overlaps
Learn it in 4 short steps
About 45m each. Track them with a timer in your plan.
- 1Choose appropriate data types~45m
- 2Pick natural or surrogate keys~45m
- 3Add foreign keys with ON DELETE rules~45m
- 4Enforce rules with CHECK and UNIQUE~45m
Key points
- Use numeric for money, timestamptz for moments in time, text for strings.
- Surrogate keys (identity columns) never change; natural keys like email can.
- ON DELETE CASCADE deletes children too; RESTRICT blocks the delete.
- Postgres does not index foreign key columns automatically; add indexes yourself.
Key terms
Tap a card to flip it. 0/6 known
Examples
CREATE TABLE bookings (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
room_id bigint NOT NULL REFERENCES rooms(id) ON DELETE RESTRICT,
guest_email text NOT NULL,
price numeric(10,2) NOT NULL CHECK (price >= 0),
start_at timestamptz NOT NULL,
end_at timestamptz NOT NULL,
CHECK (end_at > start_at),
UNIQUE (room_id, start_at)
);
CREATE INDEX ON bookings (room_id);A users table that rejects bad data
Requirements: emails are unique ignoring case, usernames are 3 to 30 characters, a status is one of three values, and the signup time is an exact moment. Step 1: text columns with CHECKs for length and allowed values. Step 2: a unique expression index on lower(email). Step 3: try a duplicate in different case and watch it fail with a clear error.
CREATE TABLE users (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL,
username text NOT NULL UNIQUE CHECK (length(username) BETWEEN 3 AND 30),
status text NOT NULL DEFAULT 'active'
CHECK (status IN ('active', 'suspended', 'deleted')),
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX users_email_lower_key ON users (lower(email));
INSERT INTO users (email, username) VALUES ('Ann@x.com', 'ann');
INSERT INTO users (email, username) VALUES ('ann@x.com', 'ann2');
-- ERROR: duplicate key value violates unique constraint "users_email_lower_key"Stopping double-booked rooms
A UNIQUE (room_id, start_at) only blocks bookings that start at exactly the same time; 10:00 to 12:00 and 11:00 to 13:00 would both be accepted. Step 1: store the booking as a tstzrange (a range of timestamptz). Step 2: enable btree_gist so the gist index can compare room_id with =. Step 3: add an exclusion constraint saying no two rows may have the same room and overlapping ranges (&&).
CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE room_bookings (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
room_id bigint NOT NULL REFERENCES rooms(id),
during tstzrange NOT NULL,
EXCLUDE USING gist (room_id WITH =, during WITH &&)
);
INSERT INTO room_bookings (room_id, during)
VALUES (1, '[2026-03-01 10:00+00, 2026-03-01 12:00+00)');
INSERT INTO room_bookings (room_id, during)
VALUES (1, '[2026-03-01 11:00+00, 2026-03-01 13:00+00)');
-- ERROR: conflicting key value violates exclusion constraintQuick reference
- id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY (preferred over serial)
- numeric(12,2) for money; never real or double precision
- text and varchar(n) are equally fast in Postgres; varchar(n) only adds a length check
- timestamptz for events; date for calendar days
- FK default is NO ACTION; add ON DELETE CASCADE only for owned children
- CREATE UNIQUE INDEX ON users (lower(email)); case-insensitive uniqueness
- UNIQUE NULLS NOT DISTINCT (PG 15+) allows at most one NULL
- \d table in psql lists columns, indexes and constraints
Common mistakes
- Storing money in float, which causes rounding errors.
- Using timestamp without time zone for events from many time zones.
- Relying only on app validation, so a script inserts bad data.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Create a products table with a unique sku, a non-empty name, a price that can't be negative, and a stock count that can't go below zero.
- Exercise 2medium
posts.author_id references users(id). When a user is deleted, their posts should stay but show no author. Write the column definition and the index.
- Exercise 3hard
Users soft-delete by setting deleted_at. Make email unique (ignoring case) among active users only, so a deleted user's email can sign up again.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Should I use varchar(255) or text in PostgreSQL?
- Use text. They are stored and processed the same way, and 255 is a habit from other databases. If a length limit is a real rule, add a CHECK or use varchar(n) on purpose.
- Does PostgreSQL create an index for a foreign key?
- No. It indexes the referenced primary key or unique column, but not the referencing column. Add one yourself, especially if you join on it or delete parent rows.
- Should I use an ENUM type or a CHECK constraint for status values?
- Both work. CHECK (status IN (...)) is easy to change in a migration. An enum type is compact and self-documenting, but removing or renaming values is harder.
- Is UUID slower than bigint as a primary key?
- A bit: UUIDs are twice as big, and random v4 UUIDs scatter inserts across the index. Time-ordered UUIDs such as v7 avoid most of the insert cost.