# DISTINCT vs GROUP BY in SQL

Source: https://sqlstreak.com/sql/distinct-vs-group-by · Tested on PostgreSQL 18.6 and SQLite 3.54.1; results generated 2026-11-22.


**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

| | DISTINCT | GROUP BY |
| --- | --- | --- |
| Returns | Each unique row once | One row per group |
| Aggregates per value | No | Yes: COUNT, SUM, AVG… |
| Filter the results | WHERE (before) | WHERE before, HAVING after |
| Reads as | “Which different values?” | “For each value, how many / how much?” |

## Examples

### DISTINCT: the different cities

```sql
SELECT DISTINCT city
FROM customers
ORDER BY city;
```

Result (both engines):

| city |
| --- |
| Austin |
| Boston |
| Chicago |
| Denver |

### GROUP BY: the same rows

```sql
SELECT city
FROM customers
GROUP BY city
ORDER BY city;
```

Result (both engines):

| city |
| --- |
| Austin |
| Boston |
| Chicago |
| Denver |

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

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

Result (both engines):

| city | customers |
| --- | --- |
| Austin | 3 |
| Denver | 3 |
| Boston | 2 |
| Chicago | 2 |

### COUNT(DISTINCT …): how many different

To count the unique values rather than list them.

```sql
SELECT COUNT(DISTINCT city) AS cities
FROM customers;
```

Result (both engines):

| cities |
| --- |
| 4 |

## 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.
