Learning navigation

Code with Animation

Primary Keys & Uniqueness

Use PRIMARY KEY, UNIQUE and NOT NULL so every row has a reliable identity and bad data is refused.

SQL6 min readConcept 4 of 44

Constraints are rules the database enforces

A constraint is a rule the database checks every time you insert or update a row. If a row breaks the rule, the database refuses it and tells you which rule failed.

NOT NULL means the column must have a value. UNIQUE means no two rows may share the same value in that column. PRIMARY KEY means the column is both unique and not null, so it identifies exactly one row.

A table can have at most one primary key, but any number of UNIQUE constraints. A key can also cover several columns together.

Rows need an identity

SQL does not label rows, and two identical rows are allowed. Without a key you cannot say "this exact row", which makes updates, deletes and links between tables unreliable.

A primary key gives every row a stable identity. Other tables can then point at it, as you will see in the next lesson.

Put the rules in the table

This members table needs a unique id, a name that is never missing, and an email that may be missing but never repeated:

CREATE TABLE members (
  id integer PRIMARY KEY,
  name text NOT NULL,
  email text UNIQUE
);

Inserting an id that already exists fails with duplicate key value violates unique constraint. Inserting a NULL name fails with violates not-null constraint. Both leave the table unchanged.

A UNIQUE column may hold NULL, and by default two NULL values do not count as equal. So you can have many rows with no email. Write UNIQUE NULLS NOT DISTINCT if you want only one.

Try to break the rules

Press the buttons to insert rows into members. Watch which rule refuses each one, and notice that two rows with no email are both accepted.

CREATE TABLE members (
id integer PRIMARY KEY,
name text NOT NULL,
email text UNIQUE
);
 
-- pick a row to insert
members (3 rows)
idintegernametextemailtext
1Ashaasha@mail.test
2Benben@mail.test
3ChenNULL

A primary key must be unique and never NULL. UNIQUE columns may hold NULL, more than once.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1Which two rules does `PRIMARY KEY` combine?
  2. 2`email` is `UNIQUE` and allows NULL. You insert two members with no email. What happens?
  3. 3How many primary keys can one table have?

Remember this

  • A constraint is a rule the database checks on every insert and update.
  • PRIMARY KEY means unique and not null, and a table has at most one.
  • UNIQUE stops repeated values but allows NULL, more than once by default.
  • A refused row leaves the table unchanged, and the error names the rule that failed.

Done with this concept?

Mark it complete to track your progress. No login needed.