๐ SQL UNIQUE โ Enforce Distinct Column Values
๐งฒ Introduction โ What is SQL UNIQUE?
The UNIQUE
constraint in SQL is used to ensure all values in a column (or set of columns) are distinct across rows. It helps maintain data integrity and prevent duplicates.
๐ฏ In this guide, youโll learn:
- How to apply the
UNIQUE
constraint - Single-column vs multi-column unique indexes
- Differences from
PRIMARY KEY
โ 1. Basic UNIQUE Constraint Syntax
CREATE TABLE users (
id INT PRIMARY KEY,
email VARCHAR(100) UNIQUE
);
โ Ensures no two users have the same email address.
๐งฑ 2. Add UNIQUE with ALTER TABLE
ALTER TABLE customers
ADD CONSTRAINT unique_email UNIQUE (email);
โ Adds a named constraint after table creation.
๐งฉ 3. Composite UNIQUE Constraint
CREATE TABLE bookings (
room_id INT,
booking_date DATE,
UNIQUE (room_id, booking_date)
);
โ Prevents double-booking a room on the same date.
๐ 4. UNIQUE vs PRIMARY KEY
Feature | PRIMARY KEY | UNIQUE Constraint |
---|---|---|
Allows NULLs | โ No | โ Yes (one or more) |
Max per table | 1 | Multiple allowed |
Implies index | โ Yes | โ Yes |
โ
Use PRIMARY KEY
for entity identity, UNIQUE
for alternate keys.
โ ๏ธ 5. Behavior Notes
- Attempting to insert a duplicate value triggers an error:
-- Error:
INSERT INTO users (email) VALUES ('test@example.com'); -- if already exists
- Can be added inline or at the end of a
CREATE TABLE
block - Index is automatically created to enforce uniqueness
๐ Best Practices
โ Recommended | โ Avoid This |
---|---|
Use UNIQUE for natural keys (email, username) | Overusing UNIQUE on optional data |
Name your constraints explicitly | Relying on auto-named constraints |
Use composite keys wisely | Assuming uniqueness applies to parts only |
๐ Summary โ Recap & Next Steps
The UNIQUE
constraint is an essential tool for preserving data integrity by ensuring that certain column values remain distinct. It supports both single and composite key enforcement.
๐ Key Takeaways:
- Prevents duplicate values in one or more columns
- Allows NULLs (unlike
PRIMARY KEY
) - Ideal for alternate keys and natural identifiers
โ๏ธ Real-World Relevance:
Used in email validation, registration systems, order codes, and inventory tracking.
โ FAQ โ SQL UNIQUE
โ What does the UNIQUE constraint do?
โ Ensures all values in the column(s) are distinct.
โ Can I have multiple UNIQUE constraints on one table?
โ Yes. Each one can apply to different column(s).
โ Can UNIQUE columns be NULL?
โ Yes. But only one NULL is allowed in most databases.
โ How is UNIQUE different from PRIMARY KEY?
โ PRIMARY KEY = 1 per table, no NULLs. UNIQUE = multiple allowed, NULLs permitted.
Share Now :