SQL > Constraint > UNIQUE Constraint

The UNIQUE constraint ensures that all values in a column are distinct.

Key Takeaway: The SQL UNIQUE constraint prevents duplicate values from being stored in a column. Unlike PRIMARY KEY, a table can have multiple UNIQUE constraints, and UNIQUE columns may allow NULLs depending on the database.

For example, in the following CREATE TABLE statement,

CREATE TABLE Customer
(SID integer UNIQUE,
Last_Name varchar (30),
First_Name varchar(30));

column "SID" has a UNIQUE constraint, and hence cannot include duplicate values. Such constraint does not hold for columns "Last_Name" and "First_Name". So, if the table already contains the following rows:

 SID  Last_Name  First_Name 
 1  Johnson  Stella 
 2  James  Gina 
 3  Aaron  Ralph 

Executing the following SQL statement,

INSERT INTO Customer VALUES (3, 'Lee', 'Grace');

will result in an error because '3' already exists in the SID column, thus trying to insert another row with that value violates the UNIQUE constraint.

Please note that a column that is specified as a primary key must also be unique. At the same time, a column that's unique may or may not be a primary key. In addition, multiple UNIQUE constraints can be defined on a table.

Frequently Asked Questions

What does the SQL UNIQUE constraint do?
The UNIQUE constraint enforces that no two rows in a table can have the same value in the constrained column. Any INSERT or UPDATE that would create a duplicate value is rejected with an error.
What is the difference between UNIQUE and PRIMARY KEY?
Both prevent duplicate values, but PRIMARY KEY also disallows NULLs and a table can have only one. A UNIQUE constraint allows NULL values (usually) and a table can have multiple UNIQUE constraints on different columns.
Can a table have multiple UNIQUE constraints?
Yes. Unlike PRIMARY KEY (only one per table), you can define as many UNIQUE constraints as needed across different columns of the same table.
Can a UNIQUE column contain NULL values?
In most databases, a UNIQUE column can hold NULL values. Some databases (like SQL Server) allow only one NULL in a unique column, while others (like MySQL) allow multiple NULLs, since NULL is not considered equal to another NULL.

Next: SQL CHECK Constraint

This page was last updated on March 19, 2026.




Copyright © 2026   1keydata.com   All Rights Reserved     Privacy Policy     About   Contact