UNIQUE Constraint Makes sure that all values in a column are different.
Example: Email addresses must be unique.
CREATE TABLE users ( user_id SERIAL PRIMARY KEY, email VARCHAR(100) UNIQUE );
Why do we need UNIQUE?
In real life, some data should never repeat.
Example: Two users cannot have the same email address.
Example: Two cars cannot have the same registration number.
That’s where the UNIQUE constraint comes in.
Step 1: Create a Table with UNIQUE Constraint
CREATE TABLE users (
user_id SERIAL PRIMARY KEY,
username VARCHAR(50) UNIQUE,
email VARCHAR(100) UNIQUE
);
Here: username must be unique. email must also be unique.
Step 2: Insert Valid Data
INSERT INTO users (username, email) VALUES ('ravi', 'ravi@example.com');
INSERT INTO users (username, email) VALUES ('kavya', 'kavya@example.com');
Both insertions succeed.
Step 3: Try Inserting Duplicate Value
INSERT INTO users (username, email) VALUES ('ravi', 'ravi123@example.com');
ERROR: duplicate key value violates unique constraint "users_username_key"
DETAIL: Key (username)=(ravi) already exists.
PostgreSQL stops us from inserting duplicate usernames.