DISTINCT: Show Unique Values

In SQL, the DISTINCT keyword returns only unique (non-duplicate) values.
This is helpful when you want to see which values exist in a column, without the same value appearing many times.


Syntax

SELECT DISTINCT column1 FROM table_name;

Example: Unique Departments

SELECT DISTINCT department FROM employees
ORDER BY department;

Output:

 department 
------------
 Finance
 HR
 IT
 Marketing
 Sales
(5 rows)

There are 20 employees, but only 5 different departments. Each department appears once.

Use DISTINCT when you care about which values exist, not how many times they appear.

Notice the ORDER BY. Without it, PostgreSQL returns the unique values in no particular order:

SELECT DISTINCT department FROM employees;

Output:

 department 
------------
 Marketing
 Finance
 Sales
 IT
 HR
(5 rows)

DISTINCT with Multiple Columns

You can also use DISTINCT with more than one column:

SELECT DISTINCT column1, column2 FROM table_name;

This returns each unique combination of values only once.

Example: Unique Department and Gender Combinations

SELECT DISTINCT department, gender FROM employees
ORDER BY department, gender;

Output:

 department | gender 
------------+--------
 Finance    | female
 Finance    | male
 HR         | female
 IT         | female
 IT         | male
 Marketing  | male
 Sales      | female
 Sales      | male
(8 rows)

This gives you every combination of department and gender in the table.

In the exercises, list the unique ages, and then the unique pairs of age and gender.