capypad
0 day streak
sql / intermediate
Snippet

Enforcing Uniqueness with Constraints

A UNIQUE constraint ensures that all values in a column are different across all rows. Unlike a PRIMARY KEY, a table can have multiple UNIQUE constraints, and they allow for data integrity and automatic index creation.

snippet.sql
sql
1
2
3
4
5
CREATE TABLE user_accounts (
user_id INTEGER PRIMARY KEY,
email_address VARCHAR(255) UNIQUE,
username VARCHAR(50) NOT NULL
);
Breakdown
1
user_id INTEGER PRIMARY KEY
Defines a unique identifier for the row that also cannot be null.
2
email_address VARCHAR(255) UNIQUE
Specifies that no two users can share the same email address.
3
username VARCHAR(50) NOT NULL
Ensures that the username field must always contain a value.