QA Interview Hub · Knowledge base · Quizzes · Українська

SQL › SELECT and filtering

What does DISTINCT do?

DISTINCT removes repeated rows from the finished result; uniqueness is counted over the whole combination of columns, and NULLs are treated as equal. A tester uses it to see the real set of values in a column, for example all statuses. Adding DISTINCT to hide row multiplication after a JOIN is a mistake: the cause remains. It is better to change the query (EXISTS or aggregate before the JOIN).

SQL · SELECT and WHERE

A report shows 120 users while the database has 85. Someone added DISTINCT and the numbers matched. Is that a fix?

A report on users with orders shows 120 rows although there are 85 users. A developer adds DISTINCT after SELECT, the number becomes 85 and the ticket is closed. But why was it 120 in the first place? This lesson explains what DISTINCT does, where a tester really needs it, and why "just add DISTINCT" often hides a bug instead of removing it.

How it works and why. DISTINCT runs after SELECT (step 6 in the logical order) and removes repeated rows from the finished result. Uniqueness is counted over the whole combination of columns in the list, not the first one: SELECT DISTINCT currency, status keeps one of each pair. For comparing values NULLs are treated as equal, so several rows with NULL merge into one. To do this the database has to find repeats: sort the result or build a hash table, so on large result sets it is not free.

SELECT DISTINCT country FROM users;            -- the list of countries
SELECT DISTINCT currency, status FROM accounts; -- unique pairs
SELECT COUNT(DISTINCT user_id) FROM accounts;   -- how many users have an account

-- for exploration GROUP BY is better: the count is visible too
SELECT status, COUNT(*) AS n
FROM transactions
GROUP BY status
ORDER BY n DESC;

The standard case for a tester: see the set of real values of a column, for example all statuses that actually exist in the table. It is a quick way to notice a value missing from the documentation ('canceled' and 'cancelled' at the same time). The variant with GROUP BY and COUNT(*) also shows how rare each value is.

What DISTINCT does with a pair of columns

accounts (input)
idcurrencystatus
1PLNactive
2PLNactive dup
3EURactive
4EURclosed
5PLNactive dup
DISTINCT currency, status
currencystatus
PLNactive
EURactive
EURclosed
Figure 1. Uniqueness is by the pair: the pairs with ids 1, 2 and 5 are identical and one stays. The two different EUR pairs both stay.

Example: DISTINCT as a patch. A developer sees that users repeat after a JOIN and adds DISTINCT. The row count becomes right, but the cause remains: in a JOIN a user's row multiplies by the number of their orders (the lesson on row growth after a JOIN has the details). If the query has a sum, DISTINCT no longer saves it, because it was computed over the multiplied set. It is better to understand why there are too many rows and join through EXISTS or aggregate before the JOIN.

What to do about duplicates after a JOIN

Typical

add DISTINCT

The row count matched, but sums over the multiplied set stay wrong and the cause is hidden. The query is also slower.

Better

find the cause

Find out by which key the rows multiplied and fix the query: EXISTS instead of JOIN or an aggregate before the join.

Figure 2. DISTINCT is right when duplicates are expected and unimportant (a list of unique values), not to mask a mistake.

Limits and alternatives. PostgreSQL has DISTINCT ON (col): it keeps the first row for each value of col in ORDER BY order, which is handy for "the user's latest transaction". Other databases do it with the window function ROW_NUMBER() (the lesson on top N per group). COUNT(DISTINCT col) ignores NULL and counts unique values. DISTINCT and ORDER BY together have a restriction: in PostgreSQL the sort expressions must be in the SELECT list, otherwise it is an error. To merge two queries without duplicates there is UNION (unlike UNION ALL, which keeps repeats): the lesson on UNION covers the difference.

-- PostgreSQL: one row per user_id, the newest transaction
SELECT DISTINCT ON (user_id) user_id, id, created_at
FROM transactions
ORDER BY user_id, created_at DESC;

SELECT DISTINCT status FROM transactions ORDER BY created_at;
-- PostgreSQL: ERROR: for SELECT DISTINCT, ORDER BY expressions
--             must appear in select list

Common mistakes.

  • DISTINCT to fix row multiplication after a JOIN: sums and query logic stay wrong.
  • Thinking DISTINCT a, b makes only a unique.
  • DISTINCT on a large table without need: extra sorting or hashing.
  • Expecting COUNT(DISTINCT col) to count NULL too.
  • Sorting by a column that is not in the SELECT DISTINCT list: an error in PostgreSQL.

Check yourself

What does SELECT DISTINCT currency, status return if the table has (PLN, active) three times and (EUR, active) once?

Answer

Two rows: (PLN, active) and (EUR, active). Uniqueness is counted by the pair, not by individual columns.

After a JOIN users repeat in a report and a colleague suggests adding DISTINCT. What do you check first?

Answer

Why the rows multiplied: by which key one user has several pairs. If the query has a sum or a counter, DISTINCT will not fix them. It is better to change the query (EXISTS or an aggregate before the JOIN) than to mask the duplicates.

How does COUNT(DISTINCT user_id) differ from COUNT(user_id)?

Answer

COUNT(user_id) counts all non-NULL values, repeats included. COUNT(DISTINCT user_id) counts only different values. Both ignore NULL.

In an interview. Junior: DISTINCT removes duplicates from the result, and uniqueness is counted over the whole combination of columns. I use it to see the set of possible values, for example all statuses in a table: it is easy to notice a value that is not in the documentation. Middle/Senior: DISTINCT runs after SELECT and needs sorting or hashing, and it treats NULLs as equal. I do not use it to hide row multiplication after a JOIN: sums and logic stay wrong. For the latest record per group I take DISTINCT ON in PostgreSQL or ROW_NUMBER in other databases.

More articles in this chapter