Skip to main content

Unique Constraints

UNIQUE constraints enforce that key values do not repeat.

This is essential for fields like email addresses, usernames, and natural keys.

Core Concepts​

Unique styleExampleUse case
Single-column uniqueemail TEXT UNIQUEOne unique value per row
Composite uniqueUNIQUE(first_name, last_name, birth_date)Unique combinations
CREATE TABLE users (
user_id INTEGER PRIMARY KEY,
email TEXT UNIQUE,
name TEXT NOT NULL
);
Expected output
Table created with one unique column (email).

Code Examples​

-- Show indexes created for unique enforcement.
PRAGMA index_list(users);
seqnameuniqueoriginpartial
0sqlite_autoindex_users_11u0

SQLite-Specific Nuances​

SQLite Nuance

SQLite allows multiple NULL values in a UNIQUE column because NULL is treated as distinct for uniqueness checks.

Common Pitfalls / Best Practices​

Pitfall

Assuming UNIQUE on email also prevents NULL values.

Use NOT NULL with UNIQUE when every row must have a value.

Best Practice

Combine NOT NULL + UNIQUE for business identifiers like email, username, and external IDs.

Quick Challenge​

Create an accounts table where username is required and unique.

View Solution
CREATE TABLE accounts (
account_id INTEGER PRIMARY KEY,
username TEXT NOT NULL UNIQUE
);
Expected output
Table created with strict unique username rule.