SQL Tutorial SQL Advanced SQL Database SQL Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

SQL UNIQUE Keyword



The SQL UNIQUE keyword is a operator and it is used to check whether the sub-query has any duplicate values in the result. It returns true if the sub-query has no duplicate values, else returns false.

Syntax

The syntax for using UNIQUE operator is given below:

SELECT table1.column
FROM table1
WHERE UNIQUE (
SELECT table2.column
FROM table2
WHERE table1.column = table2.column);

Example:

Consider a database tables called Employee and Contact_Info with the following records:

Table 1: Employee table

EmpIDNameCityAgeSalary
1JohnLondon253000
2MarryNew York242750
3JoParis272800
4KimAmsterdam303100
5RameshNew Delhi283000
6HuangBeijing282800

Table 2: Contact_Info table

Phone_NumberEmpIDAddressGender
+1-80XXXXX0002XXX, Brooklyn, New York, USAF
+33-14XXXXX013XXX, Grenelle, Paris, FranceM
+31-20XXXXX194XXX, Geuzenveld, Amsterdam, NetherlandsF
+86-10XXXXX4586XXX, Yizhuangzhen, Beijing, ChinaM
+65-67XXXXX47XXX, Yishun, SingaporeM
+81-35XXXXX728XXX, Koto City, Tokyo, JapanM

To find all the employees whose contact information is updated in the Contact_Info table, the below mentioned SQL code can be used.

SELECT Employee.EmpID, Employee.Name
FROM Employee
WHERE UNIQUE (
SELECT Contact_Info.column
FROM Contact_Info
WHERE Employee.EmpID = Contact_Info.EmpID);

This will produce the following result:

EmpIDName
2Marry
3Jo
4Kim
6Huang

Please note that, if the sub-query has duplicate values, the query will show an error.


❮ SQL Keywords

5