SQL > Constraint > UNIQUE Constraint

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

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.

Next: SQL CHECK Constraint

This page was last updated on June 19, 2023.




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