Constraints and Indexes
Unique Constraint
Preventing Duplicates
A unique constraint says a column value may appear only once.
Program
Play the script to store accounts with unique emails.
unique_constraint.sql
Replay: real traced execution (multi-file project)
CREATE TABLE accounts (id INTEGER PRIMARY KEY, email TEXT UNIQUE);
INSERT INTO accounts VALUES (1, 'ada@example.com'), (2, 'lin@example.com');
SELECT email FROM accounts ORDER BY email;
tables ← 1 row
1CREATE TABLE accounts (id INTEGER PRIMARY KEY, email TEXT UNIQUE);2INSERT INTO accounts VALUES (1, 'ada@example.com'), (2, 'lin@example.com');values this step1 rowtablesaccounts ← 2 rows
1CREATE TABLE accounts (id INTEGER PRIMARY KEY, email TEXT UNIQUE);2INSERT INTO accounts VALUES (1, 'ada@example.com'), (2, 'lin@example.com');3SELECT email FROM accounts ORDER BY email;values this step2 rowsaccountsresult ← 2 rows
2INSERT INTO accounts VALUES (1, 'ada@example.com'), (2, 'lin@example.com');3SELECT email FROM accounts ORDER BY email;values this step2 rowsresult
Follow the Emails
accountshasid INTEGER PRIMARY KEYandemail TEXT UNIQUE.- The script inserts id
1withada@example.com. - It inserts id
2withlin@example.com. UNIQUEmeans those email values cannot be duplicated in this table.ORDER BY emailreturnsada@example.combeforelin@example.com. | id | email | final order | | --- | --- | --- | | 1 | ada@example.com | 1 | | 2 | lin@example.com | 2 |
UNIQUE
`UNIQUE` prevents duplicate values in a column.
constraint
A constraint is a rule the database enforces.
data quality
Unique emails avoid duplicate account identity.
Exercise: unique_constraint.sql
Reproduce the ordered emails, then identify which column the UNIQUE rule protects from duplicates.