sqlstreak

SQL compared

DISTINCT vs GROUP BY in SQL

Updated · Tested on PostgreSQL 18.6 and SQLite 3.54.1 (results generated , re-checked on every release)

Short answer

For a list of unique values they are interchangeable: SELECT DISTINCT city and SELECT city … GROUP BY city return the same rows. Use GROUP BY when you also want an aggregate per value (a count, a sum); use DISTINCT when you only want the unique rows.

Side by side

DISTINCTGROUP BY
ReturnsEach unique row onceOne row per group
Aggregates per valueNoYes: COUNT, SUM, AVG…
Filter the resultsWHERE (before)WHERE before, HAVING after
Reads as“Which different values?”“For each value, how many / how much?”

The same data, each way

Every query below was run on PostgreSQL and SQLite when this page was built; the tables are what came back.

DISTINCT: the different cities

SELECT DISTINCT city
FROM customers
ORDER BY city;

Result (PostgreSQL and SQLite, identical): 4 rows

city
Austin
Boston
Chicago
Denver

Try it: PostgreSQL playground · SQLite playground

GROUP BY: the same rows

SELECT city
FROM customers
GROUP BY city
ORDER BY city;

Result (PostgreSQL and SQLite, identical): 4 rows

city
Austin
Boston
Chicago
Denver

Try it: PostgreSQL playground · SQLite playground

GROUP BY with a count: what DISTINCT can't do

SELECT city, COUNT(*) AS customers
FROM customers
GROUP BY city
ORDER BY customers DESC, city;

Result (PostgreSQL and SQLite, identical): 4 rows

citycustomers
Austin3
Denver3
Boston2
Chicago2

Try it: PostgreSQL playground · SQLite playground

COUNT(DISTINCT …): how many different

To count the unique values rather than list them.

SELECT COUNT(DISTINCT city) AS cities
FROM customers;

Result (PostgreSQL and SQLite, identical): 1 row

cities
4

Try it: PostgreSQL playground · SQLite playground

When to use which

DISTINCT

Removing duplicate rows from a result: the different cities, the species in the shelter.

GROUP BY

Anything per value: customers per city, revenue per category, the latest date per person.

Common mistakes

  • DISTINCT on several columns removes duplicate combinations, not duplicate values of the first column.

  • Adding DISTINCT to hide duplicates caused by a join: find the join that multiplies rows instead.

  • Selecting a column that isn't grouped next to an aggregate: PostgreSQL rejects it; SQLite picks a value from an arbitrary row.

PostgreSQL and SQLite

Everything on this page works the same in PostgreSQL and SQLite: each example above was run on both, and the results match.

Official documentation

Go deeper

Make it stick in five minutes a day

“Shape your results” teaches this step by step on a real database, with instant feedback. Free, no account needed.

Start the lesson