UNIQUE in SQL

The UNIQUE function lists each different value in a range once; in SQL this is SELECT DISTINCT.

The Excel version

=UNIQUE(B2:B500)

The SQL equivalent

This example assumes: sales(id bigint, region text, amount numeric, sale_date date). It is written in PostgreSQL syntax, and your table and column names will differ from these.

SELECT DISTINCT region
FROM sales
WHERE region IS NOT NULL
ORDER BY region;

How it works

  • DISTINCT removes repeated rows from the result, so each region appears once.
  • ORDER BY gives a predictable order; UNIQUE keeps the order of first appearance.
  • To count the unique values instead of listing them, use COUNT(DISTINCT region).

Where the results differ from Excel

  • Excel's UNIQUE treats 'West' and 'west' as the same value, while SQL's DISTINCT treats them as different unless you normalise the case.
  • UNIQUE on several columns returns unique combinations, as DISTINCT col1, col2 does in SQL.
  • Blank cells appear as a zero or blank entry in UNIQUE; in SQL nulls appear as one null row unless you filter them.

Skip the query: ask in plain English

If you would rather not write SQL, type the question. SchemaChat turns it into SQL against your connected database or uploaded file, runs it, and shows the SQL and the figures it used so you can check the answer before you share it. Check that the result matches how your spreadsheet defines the number.

  • List the different regions we sell in.
  • How many distinct customers bought something this year?

Frequently asked questions

What is the SQL equivalent of UNIQUE?
The UNIQUE function lists each different value in a range once; in SQL this is SELECT DISTINCT.
How does the SQL version of UNIQUE work?
DISTINCT removes repeated rows from the result, so each region appears once. ORDER BY gives a predictable order; UNIQUE keeps the order of first appearance. To count the unique values instead of listing them, use COUNT(DISTINCT region).
Why can SQL give a different result from UNIQUE?
Excel's UNIQUE treats 'West' and 'west' as the same value, while SQL's DISTINCT treats them as different unless you normalise the case.