PostgreSQL – DISTINCT Clause

A DISTINCT clause is used in the select statement to return only the distinct values from a data set.

Consider the employee table as shown below:

idfirst_namelast_namedepartmentsalary
101bryanwalkersales50,000
102alexcarpenteraccounts55,000
103samwhitesales60,000
104johnbarrysales54,000
105billwoodaccounts65,000
106roberthopkinssupport70,000
107davidleesupport72,000
108jacksearssupport65,000
109tomyoungsales55,000
employee

I would like to query all the departments from the employee table.

SELECT department FROM employee;

department
----------
sales
accounts
sales
sales
accounts
support
support
support
sales

But what if I would like to return each department name only once ? DISTINCT clause does just that. It removes duplicates from the result set.

SELECT DISTINCT department FROM employee;

department
----------
sales
accounts
support

Also check out DISTINCT ON clause and COUNT DISTINCT.

See also  PostgreSQL - Escape single quote