๐Ÿงท SQL Constraints & Indexes
Estimated reading: 2 minutes 28 views

๐Ÿ” 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

FeaturePRIMARY KEYUNIQUE Constraint
Allows NULLsโŒ Noโœ… Yes (one or more)
Max per table1Multiple 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 explicitlyRelying on auto-named constraints
Use composite keys wiselyAssuming 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

๐Ÿ” SQL UNIQUE

Or Copy Link

CONTENTS
Scroll to Top