// dialect comparison

DISTINCT on an expression

DISTINCT works on computed values the same way it works on columns.

Filed under Querying

The verdict

The query itself is fully portable. The result is not: the same DISTINCT email returns fewer rows on SQL Server and MySQL than on PostgreSQL, SQLite and Oracle, because their default collations ignore case. Write the folding expression explicitly when the count matters. DISTINCT ON exists only in PostgreSQL.

Where they differ

Any expression can follow DISTINCT and the engine deduplicates the computed values. The syntax is identical in all five engines. What differs is how the comparison treats case: on SQL Server and MySQL's default collations, DISTINCT email already merges '[email protected]' and '[email protected]'.

How each engine writes it

SQL Server

SELECT DISTINCT LOWER(email) FROM users;

With the default case-insensitive collation, DISTINCT email returns the same count, and which casing you see for each group is arbitrary.

PostgreSQL

SELECT DISTINCT LOWER(email) FROM users;

Comparison is case-sensitive, so LOWER() changes the result. DISTINCT ON (LOWER(email)) * … ORDER BY LOWER(email), id keeps one full row per value.

MySQL

SELECT DISTINCT LOWER(email) FROM users;

Default *_ci collations already fold case (utf8mb4_0900_ai_ci also folds accents), so DISTINCT email gives the same count.

SQLite

SELECT DISTINCT lower(email) FROM users;

Case-sensitive by default. lower() folds ASCII letters only unless the ICU extension is loaded.

Oracle

SELECT DISTINCT LOWER(email) FROM users;

Case-sensitive by default. SELECT UNIQUE is an old Oracle synonym for DISTINCT.

Questions that come up

Does DISTINCT apply to one column or the whole row?

The whole result row. SELECT DISTINCT a, b returns distinct (a, b) pairs; there is no way to deduplicate on one column while returning others. For that, use GROUP BY with aggregates, ROW_NUMBER() … WHERE rn = 1, or PostgreSQL's DISTINCT ON.

Why does DISTINCT email return different counts on different engines?

Collation. SQL Server's and MySQL's default collations compare '[email protected]' and '[email protected]' as equal, so DISTINCT keeps one. PostgreSQL, SQLite and Oracle compare bytes by default and keep both. DISTINCT LOWER(email) gives the same count everywhere (for ASCII data).

What does DISTINCT ON give me that GROUP BY doesn't?

A complete row per group without aggregating every other column. The ORDER BY decides which row wins: DISTINCT ON (customer_id) * … ORDER BY customer_id, created_at DESC keeps each customer's newest order. The leading ORDER BY expressions must match the DISTINCT ON list.

Keep reading

// write it once, run it anywhere

Switch engines without relearning SQL

SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.