Advertisement
❮ Previous: SQL Select Next: SQL Where ❯

SQL Select Distinct

The SELECT DISTINCT statement is used to remove duplicate rows from your query results and return only unique values.

When a database table contains repetitive information (like a list of customers where many live in the same city), DISTINCT filters out the duplicates so you see each value exactly once.


Basic Syntax for a Single Column

To find all unique values within one specific column, place DISTINCT immediately after SELECT.

SELECT DISTINCT column_name
FROM table_name;

Real-World Example:

Imagine you have an employees table, and multiple people work in the same department.

-- This returns a clean list of unique departments, hiding duplicates

SELECT DISTINCT department
FROM employees;

Using DISTINCT with Multiple Columns

When you list multiple columns after DISTINCT, SQL evaluates the combination of those columns.

A row is only hidden if the exact combination of all selected columns repeats.

-- Returns unique combinations of department AND job_title

SELECT DISTINCT department, job_title
FROM employees;

If "Sales" has three "Managers" and two "Associates", the output will display "Sales | Manager" once and "Sales | Associate" once.


Counting Unique Values (COUNT)

You can combine DISTINCT with the COUNT() function to find the exact number of unique items in a column.

-- Calculates the total number of unique cities your customers live in

SELECT COUNT(DISTINCT city) AS unique_city_count
FROM customers;

Note: COUNT(DISTINCT column) automatically ignores NULL values in most database platforms).


Key Rules to Remember

❮ Previous: SQL Select Next: SQL Where ❯
Advertisement