SQL DISTINCT

The DISTINCT keyword in SQL is used to remove duplicate values from the result of a query. It returns only unique (different) values.

Basic Syntax

SELECT DISTINCT column_name
FROM table_name;

DISTINCT on One Column

SELECT DISTINCT city
FROM students;

Explanation:
Even though Delhi and Mumbai appear multiple times, they are shown only once.

DISTINCT on Multiple Columns

SELECT DISTINCT city, name
FROM students;

Explanation:
Returns unique combinations of city and name.

DISTINCT with COUNT(): Count the number of unique cities.

SELECT COUNT(DISTINCT city)
FROM students;

Example Without DISTINCT

SELECT city
FROM students;

Result may contain duplicates.


Topics