CREATE TABLE and Constraints: NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, CHECK and DEFAULT
How to create tables that protect their data: column definitions, DEFAULT, NOT NULL, UNIQUE and NULLs, PRIMARY KEY, FOREIGN KEY, column and table CHECK constraints, naming constraints, generated columns, exclusion constraints for overlapping ranges, and deferrable constraints.
kvi5hnuCode Sprout team member10 min readOn this page
A table definition does two jobs. It describes the shape of the data, its columns and types, and it states the rules the data must follow: every member has a name, no two members share an email address, points are never negative, a referral points to a real member. Those rules are constraints, and the database enforces them on every insert and update, from every application, script and person, forever.
Constraints are the cheapest bug prevention there is. A rule enforced only in application code is skipped by the next import script, the admin running a manual fix, or the second application written two years later. This article covers CREATE TABLE and every kind of constraint. Article 53 covers changing tables afterwards, and article 54 covers generating keys.
CREATE TABLE
-- A table with every common kind of constraint, each one named
CREATE TABLE members (
member_id INTEGER GENERATED ALWAYS AS IDENTITY,
email VARCHAR(254) NOT NULL,
name VARCHAR(80) NOT NULL,
tier VARCHAR(10) NOT NULL DEFAULT 'basic',
points INTEGER NOT NULL DEFAULT 0,
joined_on DATE NOT NULL DEFAULT CURRENT_DATE,
referred_by INTEGER,
CONSTRAINT members_pk PRIMARY KEY (member_id),
CONSTRAINT members_email_uq UNIQUE (email),
CONSTRAINT members_tier_ck CHECK (tier IN ('basic', 'silver', 'gold')),
CONSTRAINT members_points_ck CHECK (points >= 0),
CONSTRAINT members_referrer_fk FOREIGN KEY (referred_by) REFERENCES members (member_id)
);
INSERT INTO members (email, name) VALUES ('asha@example.com', 'Asha Rao');
INSERT INTO members (email, name, tier, points, referred_by)
VALUES ('ben@example.com', 'Ben Okafor', 'silver', 120, 1);
SELECT member_id, email, tier, points, referred_by, joined_on = CURRENT_DATE AS joined_today
FROM members ORDER BY member_id;
member_id | email | tier | points | referred_by | joined_today
-----------+------------------+--------+--------+-------------+--------------
1 | asha@example.com | basic | 0 | | t
2 | ben@example.com | silver | 120 | 1 | t
(2 rows)
A table definition lists its columns, each with a name, a data type (article 35) and optional column constraints, followed by optional table constraints:
CREATE TABLE table_name (
column_name data_type [DEFAULT expr] [NOT NULL] [column constraints],
...,
[CONSTRAINT name] table_constraint,
...
);
Most constraints can be written either way: email VARCHAR(254) UNIQUE as a column constraint, or CONSTRAINT members_email_uq UNIQUE (email) as a table constraint. Constraints that involve several columns, such as a composite primary key or a CHECK comparing two dates, must be table constraints.
Some practical points:
CREATE TABLE IF NOT EXISTSdoes nothing, without an error, if the table exists, which is useful in setup scripts. It doesn't check that the existing table has the same definition.CREATE TABLE new_t (LIKE old_t INCLUDING ALL)copies a table's structure, including defaults,CHECKandNOT NULLconstraints and indexes, but not foreign keys and no rows.CREATE TABLE ... AS SELECT(article 31) copies rows but no constraints.CREATE TEMPORARY TABLEcreates a table visible only to the current session and dropped when it ends.- Unquoted names are folded to lower case in PostgreSQL. Use lower-case names with underscores, and avoid quoted identifiers like
"Order Items", which must then be quoted everywhere.
DEFAULT
A DEFAULT gives the value a column gets when an insert leaves it out (article 31). Asha's member row got the tier 'basic', 0 points and today's date without mentioning them. Defaults can be constants or expressions such as CURRENT_DATE or now(), and are evaluated at insert time.
A default isn't a constraint: it's used only when the column is omitted or the keyword DEFAULT is used. An explicit NULL is still stored as NULL, unless NOT NULL forbids it.
The constraints

-- A table with every common kind of constraint, each one named
CREATE TABLE members (
member_id INTEGER GENERATED ALWAYS AS IDENTITY,
email VARCHAR(254) NOT NULL,
name VARCHAR(80) NOT NULL,
tier VARCHAR(10) NOT NULL DEFAULT 'basic',
points INTEGER NOT NULL DEFAULT 0,
joined_on DATE NOT NULL DEFAULT CURRENT_DATE,
referred_by INTEGER,
CONSTRAINT members_pk PRIMARY KEY (member_id),
CONSTRAINT members_email_uq UNIQUE (email),
CONSTRAINT members_tier_ck CHECK (tier IN ('basic', 'silver', 'gold')),
CONSTRAINT members_points_ck CHECK (points >= 0),
CONSTRAINT members_referrer_fk FOREIGN KEY (referred_by) REFERENCES members (member_id)
);
INSERT INTO members (email, name) VALUES ('asha@example.com', 'Asha Rao');
INSERT INTO members (email, name, tier, points, referred_by)
VALUES ('ben@example.com', 'Ben Okafor', 'silver', 120, 1);
-- Each constraint rejects its own kind of bad data; the error names the constraint
INSERT INTO members (email, name) VALUES ('asha@example.com', 'Asha again');
INSERT INTO members (email, name, tier, joined_on) VALUES ('chen@example.com', 'Chen Wei', 'platinum', DATE '2026-03-01');
INSERT INTO members (email, name, points, joined_on) VALUES ('dana@example.com', 'Dana Cruz', -5, DATE '2026-03-01');
INSERT INTO members (email, name, referred_by) VALUES ('eli@example.com', 'Eli Novak', 42);
INSERT INTO members (email, joined_on) VALUES ('farah@example.com', DATE '2026-03-01');
INSERT INTO members (member_id, email, name) VALUES (99, 'gil@example.com', 'Gil');
SELECT COUNT(*) AS members FROM members;
psql:/workspace/solution.sql:23: ERROR: duplicate key value violates unique constraint "members_email_uq"
DETAIL: Key (email)=(asha@example.com) already exists.
psql:/workspace/solution.sql:24: ERROR: new row for relation "members" violates check constraint "members_tier_ck"
DETAIL: Failing row contains (4, chen@example.com, Chen Wei, platinum, 0, 2026-03-01, null).
psql:/workspace/solution.sql:25: ERROR: new row for relation "members" violates check constraint "members_points_ck"
DETAIL: Failing row contains (5, dana@example.com, Dana Cruz, basic, -5, 2026-03-01, null).
psql:/workspace/solution.sql:26: ERROR: insert or update on table "members" violates foreign key constraint "members_referrer_fk"
DETAIL: Key (referred_by)=(42) is not present in table "members".
psql:/workspace/solution.sql:27: ERROR: null value in column "name" of relation "members" violates not-null constraint
DETAIL: Failing row contains (7, farah@example.com, null, basic, 0, 2026-03-01, null).
psql:/workspace/solution.sql:28: ERROR: cannot insert a non-DEFAULT value into column "member_id"
DETAIL: Column "member_id" is an identity column defined as GENERATED ALWAYS.
HINT: Use OVERRIDING SYSTEM VALUE to override.
members
---------
2
(1 row)
Each failed insert is rejected with an error naming the broken constraint, and the table still has its 2 rows:
NOT NULL: the column must have a value. Farah's row has no name. Make every columnNOT NULLunless there's a real reason for it to be missing (article 8): optional columns spread NULL handling into every query.CHECK (condition): every row must satisfy a condition. Chen's tier,'platinum', isn't in the allowed list, and Dana's points are negative. ACHECKcan use any expression on the row's own columns, includingINlists, ranges,LIKEand regular expressions (article 42).UNIQUE: no two rows may have the same value, or combination of values, in the listed columns. The secondasha@example.comis rejected. AUNIQUEconstraint is implemented with an index, which also speeds up searches on the column.PRIMARY KEY: the row's identifier. It'sUNIQUEplusNOT NULL, and a table can have only one. Every table should have one.FOREIGN KEY ... REFERENCES: the value must exist in the referenced table's primary key or unique column, or be NULL. Eli's referrer, member 42, doesn't exist. Article 53 covers what happens when a referenced row is deleted.
Two more details appear in the output. The identity column member_id rejects explicit values, because it's GENERATED ALWAYS (article 54). And the failing rows show the IDs 4, 5 and 7: a failed insert still consumes an identity value, so gaps in the numbering are normal and harmless.
Name your constraints. CONSTRAINT members_email_uq UNIQUE (email) produces the error violates unique constraint "members_email_uq", which tells a developer, or the application's error handler, exactly what went wrong. Unnamed constraints get generated names, which differ between databases and make later ALTER TABLE ... DROP CONSTRAINT statements harder to write. A common convention is table_column_suffix, with pk, fk, uq and ck suffixes.
UNIQUE, CHECK and NULL
\pset null '(null)'
-- UNIQUE and NULL: by default, NULLs don't conflict with each other
CREATE TABLE loyalty_cards (
card_id INTEGER PRIMARY KEY,
phone TEXT UNIQUE
);
INSERT INTO loyalty_cards VALUES (1, NULL), (2, NULL), (3, '+44 20 7946 0018');
SELECT COUNT(*) AS cards_without_phone FROM loyalty_cards WHERE phone IS NULL;
-- NULLS NOT DISTINCT (PostgreSQL 15+): at most one NULL
CREATE TABLE gift_cards (
card_id INTEGER PRIMARY KEY,
code TEXT,
CONSTRAINT gift_cards_code_uq UNIQUE NULLS NOT DISTINCT (code)
);
INSERT INTO gift_cards VALUES (1, NULL);
INSERT INTO gift_cards VALUES (2, NULL);
-- A CHECK that is NULL passes: NULL isn't false
CREATE TABLE returns (
return_id INTEGER PRIMARY KEY,
qty INTEGER CHECK (qty > 0)
);
INSERT INTO returns VALUES (1, NULL);
SELECT * FROM returns;
cards_without_phone
---------------------
2
(1 row)
psql:/workspace/solution.sql:18: ERROR: duplicate key value violates unique constraint "gift_cards_code_uq"
DETAIL: Key (code)=(null) already exists.
return_id | qty
-----------+--------
1 | (null)
(1 row)
NULL means "unknown", and that affects constraints in two ways:
UNIQUEallows several NULLs. Two unknown phone numbers aren't known to be equal, so both loyalty cards without a phone are accepted. That's the standard behaviour, followed by PostgreSQL, MySQL, Oracle (for single-column keys) and SQLite. SQL Server is the exception: its unique constraints allow only one NULL, and a filtered unique index (WHERE phone IS NOT NULL) is the workaround. PostgreSQL 15 addedUNIQUE NULLS NOT DISTINCT, which treats NULLs as equal, so the second gift card without a code is rejected.- A
CHECKpasses when its condition is NULL. A check fails only when the condition is false.qty > 0with a NULL quantity is unknown, so the row is accepted. If NULL shouldn't be allowed, addNOT NULL.
Table CHECKs and generated columns
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Table-level CHECK constraints compare columns; generated columns compute values
CREATE TABLE promotions (
promo_id INTEGER PRIMARY KEY,
product_id INTEGER NOT NULL REFERENCES products (product_id),
starts_on DATE NOT NULL,
ends_on DATE NOT NULL,
list_price DECIMAL(8, 2) NOT NULL,
pct_off INTEGER NOT NULL CHECK (pct_off BETWEEN 1 AND 90),
sale_price DECIMAL(8, 2) GENERATED ALWAYS AS (ROUND(list_price * (100 - pct_off) / 100, 2)) STORED,
CONSTRAINT promotions_dates_ck CHECK (ends_on > starts_on)
);
INSERT INTO promotions (promo_id, product_id, starts_on, ends_on, list_price, pct_off)
VALUES (1, 1, DATE '2026-07-01', DATE '2026-07-15', 249.99, 20),
(2, 7, DATE '2026-07-01', DATE '2026-08-01', 16.00, 25);
SELECT promo_id, list_price, pct_off, sale_price FROM promotions ORDER BY promo_id;
-- The dates are checked against each other; generated columns can't be written
INSERT INTO promotions (promo_id, product_id, starts_on, ends_on, list_price, pct_off)
VALUES (3, 3, DATE '2026-07-10', DATE '2026-07-01', 34.50, 10);
UPDATE promotions SET sale_price = 1.00 WHERE promo_id = 1;
promo_id | list_price | pct_off | sale_price
----------+------------+---------+------------
1 | 249.99 | 20 | 199.99
2 | 16.00 | 25 | 12.00
(2 rows)
psql:/workspace/solution.sql:81: ERROR: new row for relation "promotions" violates check constraint "promotions_dates_ck"
DETAIL: Failing row contains (3, 3, 2026-07-10, 2026-07-01, 34.50, 10, 31.05).
psql:/workspace/solution.sql:82: ERROR: column "sale_price" can only be updated to DEFAULT
DETAIL: Column "sale_price" is a generated column.
- A table-level
CHECKcan compare columns: a promotion must end after it starts. The third promotion ends before it begins and is rejected. Checks can only see the row being written, not other rows or other tables. Rules that involve other rows need aUNIQUEor exclusion constraint, a foreign key, or a trigger (article 65). - A generated column computes its value from other columns of the same row.
sale_priceis always the list price minus the discount, so it can never disagree with them, which makes it the safest form of denormalization (article 51). Trying to write to it is an error.STOREDcomputes the value on write and stores it. PostgreSQL 18 also supportsVIRTUALcolumns, computed when read, and made them the default. MySQL, SQL Server (computed columns) and Oracle (virtual columns) have the same feature.
Exclusion constraints
UNIQUE stops two rows having equal values. Some rules need to stop two rows overlapping: two bookings of one pitch, two prices for one product valid at the same time. PostgreSQL's exclusion constraint generalises UNIQUE to any operator:
-- An exclusion constraint: no two bookings of the same pitch may overlap
CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE pitch_bookings (
booking_id INTEGER PRIMARY KEY,
pitch TEXT NOT NULL,
stay DATERANGE NOT NULL,
CONSTRAINT no_double_booking EXCLUDE USING gist (pitch WITH =, stay WITH &&)
);
INSERT INTO pitch_bookings VALUES
(1, 'A', DATERANGE('2026-07-01', '2026-07-04')), -- [1 Jul, 4 Jul): departs on the 4th
(2, 'A', DATERANGE('2026-07-04', '2026-07-06')), -- arrives on the 4th: touching, not overlapping
(3, 'B', DATERANGE('2026-07-02', '2026-07-05')); -- another pitch: no conflict
SELECT booking_id, pitch, stay, upper(stay) - lower(stay) AS nights
FROM pitch_bookings ORDER BY booking_id;
-- This overlaps booking 1 on pitch A and is rejected
INSERT INTO pitch_bookings VALUES (4, 'A', DATERANGE('2026-07-03', '2026-07-05'));
booking_id | pitch | stay | nights
------------+-------+-------------------------+--------
1 | A | [2026-07-01,2026-07-04) | 3
2 | A | [2026-07-04,2026-07-06) | 2
3 | B | [2026-07-02,2026-07-05) | 3
(3 rows)
psql:/workspace/solution.sql:19: ERROR: conflicting key value violates exclusion constraint "no_double_booking"
DETAIL: Key (pitch, stay)=(A, [2026-07-03,2026-07-05)) conflicts with existing key (pitch, stay)=(A, [2026-07-01,2026-07-04)).
stayis adaterange, a range type that holds a start and an end.DATERANGE('2026-07-01', '2026-07-04')is half-open, written[2026-07-01,2026-07-04): it includes 1 July and excludes 4 July, the departure date (article 40).EXCLUDE USING gist (pitch WITH =, stay WITH &&)rejects a new row if an existing row has an equal pitch and an overlapping (&&) stay. Booking 2 arrives the day booking 1 leaves, so the half-open ranges only touch, and both are accepted. Booking 4 overlaps booking 1 and is rejected.- The
btree_gistextension lets the GiST index handle the plain=comparison onpitch.
Without this, preventing double bookings needs careful locking in the application, and concurrent requests make it easy to get wrong (article 61). With it, the database guarantees the rule. PostgreSQL 18 adds the standard form for primary and unique keys, PRIMARY KEY (pitch, stay WITHOUT OVERLAPS). Other databases have no direct equivalent and rely on triggers or locking.
Deferrable constraints
-- A deferrable constraint is checked at COMMIT, not after each statement
CREATE TABLE teams (
team_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
captain_id INTEGER NOT NULL
);
CREATE TABLE players (
player_id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
team_id INTEGER NOT NULL REFERENCES teams (team_id)
);
ALTER TABLE teams ADD CONSTRAINT teams_captain_fk
FOREIGN KEY (captain_id) REFERENCES players (player_id)
DEFERRABLE INITIALLY DEFERRED;
-- Each table needs a row in the other: possible only because the check waits for COMMIT
BEGIN;
INSERT INTO teams VALUES (1, 'Trail runners', 10);
INSERT INTO players VALUES (10, 'Asha Rao', 1);
COMMIT;
SELECT t.name AS team, p.name AS captain
FROM teams t JOIN players p ON p.player_id = t.captain_id;
team | captain
---------------+----------
Trail runners | Asha Rao
(1 row)
Normally, a constraint is checked at the end of each statement. Sometimes data is only valid after several statements: a team must have a captain, and the captain must be an existing player. Whichever row is inserted first, its foreign key fails.
A foreign key declared DEFERRABLE INITIALLY DEFERRED is checked at COMMIT instead (article 60). Inside the transaction, the team can refer to a player who doesn't exist yet. If the transaction ended with the rule still broken, the COMMIT would fail and nothing would be saved. SET CONSTRAINTS name DEFERRED defers a DEFERRABLE INITIALLY IMMEDIATE constraint for one transaction only. PostgreSQL and Oracle support deferrable UNIQUE, PRIMARY KEY, FOREIGN KEY and exclusion constraints. MySQL and SQL Server don't support deferral.
Constraints in other databases
| Feature | PostgreSQL | MySQL 8 | SQL Server | Oracle | SQLite |
|---|---|---|---|---|---|
CHECK enforced | yes | since 8.0.16 | yes | yes | yes |
multiple NULLs in UNIQUE | yes (NULLS NOT DISTINCT to forbid) | yes | no, only one | yes | yes |
| foreign keys | yes | yes (InnoDB) | yes | yes | only after PRAGMA foreign_keys = ON |
| generated columns | STORED, VIRTUAL (18) | STORED, VIRTUAL | computed columns | virtual columns | STORED, VIRTUAL |
| exclusion constraints | yes | no | no | no | no |
| deferrable constraints | yes | no | no | yes | foreign keys only |
Two traps stand out. MySQL before 8.0.16 parsed and silently ignored CHECK constraints, so old schemas may contain checks that never ran. And SQLite doesn't enforce foreign keys unless every connection turns them on with PRAGMA foreign_keys = ON.
What's current
- PostgreSQL 18 added virtual generated columns, made them the default, and added temporal constraints:
WITHOUT OVERLAPSfor primary and unique keys andPERIODfor foreign keys. It also allowsNOT NULLconstraints to be named and declaredNOT VALID. - PostgreSQL 15 added
UNIQUE NULLS NOT DISTINCT. - MySQL 8.0.16 began enforcing
CHECKconstraints.
Common questions
What's the difference between a primary key and a unique constraint?
A primary key is unique and NOT NULL, and a table has only one. A table can have several unique constraints, and their columns may allow NULLs.
Why did my unique column accept two NULLs?
NULLs aren't equal to each other, so standard UNIQUE constraints allow several. Use NULLS NOT DISTINCT in PostgreSQL 15+, or add NOT NULL.
Why does a CHECK constraint accept NULL?
A check fails only when its condition is false. With a NULL input, the condition is unknown, so the row passes. Add NOT NULL as well.
Can a CHECK constraint look at other rows or tables?
No. Use UNIQUE, an exclusion constraint, a foreign key or a trigger.
Should I name constraints? Yes. Names make errors understandable and later changes easier.
How do I stop overlapping date ranges?
In PostgreSQL, an exclusion constraint with a range column and the && operator. Elsewhere, a trigger or careful locking.
Summary
CREATE TABLEdefines columns, their types, defaults and constraints. Name constraints with a consistent convention.DEFAULTfills omitted columns.NOT NULLforbids missing values.CHECKenforces conditions on a row's own columns. It passes when the condition is NULL.UNIQUEforbids duplicates, but allows several NULLs except in SQL Server.PRIMARY KEYis unique and not null.FOREIGN KEYrequires a matching row in the referenced table.- Generated columns compute values that can't disagree with their sources.
- Exclusion constraints forbid overlaps, and deferrable constraints are checked at commit.
- Constraint support differs: older MySQL ignored
CHECK, and SQLite needs foreign keys switched on.
Practice questions
Write a CREATE TABLE statement for reviews with a review ID, a product ID that must exist in products, a rating from 1 to 5 that can't be missing, an optional comment, and a rule that each product can be reviewed only once per customer ID.
Answer
CREATE TABLE reviews (
review_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
product_id INTEGER NOT NULL REFERENCES products (product_id),
customer_id INTEGER NOT NULL REFERENCES customers (customer_id),
rating INTEGER NOT NULL CHECK (rating BETWEEN 1 AND 5),
comment TEXT,
CONSTRAINT reviews_one_per_customer_uq UNIQUE (product_id, customer_id)
);
A column is defined as discount INTEGER CHECK (discount BETWEEN 0 AND 50). Which of these inserts succeed: 0, 50, 60, NULL?
Answer
0, 50 and NULL. 60 fails the check. NULL makes the condition unknown, which passes. Add NOT NULL to reject it.
How many rows with a NULL email can a table with UNIQUE (email) hold in PostgreSQL, and in SQL Server?
Answer
Any number in PostgreSQL, unless the constraint is declared NULLS NOT DISTINCT. Only one in SQL Server.
Why can't a CHECK constraint enforce "no two bookings of the same pitch overlap"?
Answer
A CHECK sees only the row being inserted or updated, and this rule compares it with other rows. An exclusion constraint, EXCLUDE USING gist (pitch WITH =, stay WITH &&), enforces it in PostgreSQL.
Previous: Normalization: 1NF, 2NF, 3NF, BCNF and When to Denormalize
Next: Changing Tables: ALTER TABLE, DROP and Foreign Key Actions

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.