Sub topic 11
Combining DISTINCT with ORDER BY and LIMIT
This chapter assumes you can write basic SELECT ... FROM ... WHERE queries, sort with ORDER BY, and that you already know what DISTINCT, LIMIT, and OFFSET do on their own. Here you will combine them. The combination is where most real mistakes happen, because the clauses run in a fixed logical order that differs from the order you write them.
The order the clauses run in
You write a query top to bottom, but the database reasons about it in a different sequence. For the clauses in this chapter, the logical order is:
FROMandWHEREproduce the candidate rows.SELECTcomputes the output columns.DISTINCTremoves duplicate output rows.ORDER BYsorts what is left.OFFSETskips rows from the sorted result.LIMITkeeps the requested number of rows.
Two consequences follow. First, DISTINCT works on the rows as they look after SELECT, so it only sees the columns you selected. Second, OFFSET and LIMIT work on the sorted, de-duplicated result, so they count unique rows, not original table rows.
The database may execute the query differently, for example by using an index to avoid a sort. The result must still match this logical model.
DISTINCT, then sort, then slice
Look at this query from the plan:
SELECT DISTINCT country
FROM customers
ORDER BY country
LIMIT 5 OFFSET 5;Step by step:
- Read all rows of
customersand keep thecountrycolumn. - Remove duplicates, leaving one row per country.
- Sort the unique countries alphabetically.
- Skip the first 5 unique countries.
- Return the next 5.
If customers has 10,000 rows but only 40 countries, the offset and limit act on the 40-row list. The result is countries 6 through 10 in alphabetical order. This is what you want for something like a country dropdown that loads in pages.
Because ORDER BY country sorts every unique value, the result is deterministic. Each country appears once, so no two rows tie on the sort key.
ORDER BY can only use what DISTINCT kept
Since DISTINCT runs before ORDER BY, the sort can only use values that survive de-duplication. Suppose you want unique countries ordered by the most recent signup in each country:
SELECT DISTINCT country
FROM customers
ORDER BY created_at DESC;This fails or behaves unpredictably. A country with many customers has many created_at values, and the query does not say which one to use. PostgreSQL rejects it with an error that says ORDER BY expressions must appear in the select list for SELECT DISTINCT. Other systems may reject it or accept it and pick a value you did not choose.
There are two correct fixes. Which one you use depends on what you want.
If you want one row per country, use an aggregate and GROUP BY:
SELECT country, MAX(created_at) AS latest_signup
FROM customers
GROUP BY country
ORDER BY latest_signup DESC
LIMIT 5;If you really want unique combinations, put the sort column in the select list. This changes the meaning, because DISTINCT now applies to the pair:
SELECT DISTINCT country, created_at
FROM customers
ORDER BY created_at DESC
LIMIT 5;This returns the five most recent distinct (country, timestamp) pairs. The same country can appear several times, which is usually not what someone asking for "unique countries" wants.
Choosing the sort key for DISTINCT results
When you combine DISTINCT with multi-column output, sort by all the selected columns, or by a prefix of them that is already unique per row. Consider:
SELECT DISTINCT country, city
FROM customers
ORDER BY country, city
LIMIT 10 OFFSET 10;Here (country, city) is exactly the thing DISTINCT made unique, so sorting by both columns gives a total order with no ties. Paging through it is stable.
If you sorted only by country, many rows would tie, because a country has many cities. The database could return tied rows in a different order on each run, and a page boundary could fall in the middle of a tie. Rows could then repeat across pages or be skipped entirely. A simple rule: for SELECT DISTINCT, order by every selected column unless you can prove a shorter key is unique.
LIMIT without DISTINCT: tie-breakers
Without DISTINCT, uniqueness is not guaranteed by the query, so you add a tie-breaker yourself. This is the pattern from the plan:
SELECT order_id, order_date, total
FROM orders
ORDER BY order_date DESC, order_id DESC
LIMIT 5;Many orders can share an order_date. Adding order_id, a unique column, makes the order total. The five rows you get are then the same on every run, as long as the data does not change.
You can use the same idea with DISTINCT. If you select a unique column, DISTINCT has nothing to remove, which is a sign you may not need it.
DISTINCT versus GROUP BY for "top N unique" queries
A common request is "the top N unique values by some measure". DISTINCT cannot rank by a measure that is not in the select list, so GROUP BY is usually the right tool. Compare the two ways of asking for the five customers with the highest total spend:
SELECT customer_id, SUM(total) AS spend
FROM orders
GROUP BY customer_id
ORDER BY spend DESC, customer_id
LIMIT 5;Here GROUP BY collapses rows to one per customer, the aggregate gives the sort key, and customer_id breaks ties. Using SELECT DISTINCT customer_id would remove duplicates but lose the spend figure needed to rank.
A rough guide:
| You want | Use |
|---|---|
| The unique values of one or more columns | `SELECT DISTINCT` |
| Unique values, sorted by those same columns | `SELECT DISTINCT ... ORDER BY` those columns |
| Unique values ranked by an aggregate (sum, max, count) | `GROUP BY` with `ORDER BY` on the aggregate |
| A count of unique values | `COUNT(DISTINCT column)` |
Putting a filter and a limit around DISTINCT
WHERE runs before DISTINCT, so it reduces the input rows first. This query lists the first ten distinct cities of customers in Germany:
SELECT DISTINCT city
FROM customers
WHERE country = 'Germany'
ORDER BY city
LIMIT 10;If you need to filter on the de-duplicated result, for example "countries that have more than one city", WHERE is the wrong place, because it cannot see the outcome of DISTINCT. Use GROUP BY with HAVING, or a subquery:
SELECT country
FROM (
SELECT DISTINCT country, city
FROM customers
) AS unique_places
GROUP BY country
HAVING COUNT(*) > 1
ORDER BY country
LIMIT 5;The inner query makes unique (country, city) pairs. The outer query counts pairs per country and keeps countries with more than one. This is the same as COUNT(DISTINCT city) per country, which is shorter:
SELECT country
FROM customers
GROUP BY country
HAVING COUNT(DISTINCT city) > 1
ORDER BY country
LIMIT 5;Common errors and how to spot them
- Sorting by a column that is not selected.
SELECT DISTINCT a ... ORDER BY bis rejected in PostgreSQL and can give arbitrary results elsewhere. Addbto the list with the right meaning, or switch toGROUP BY. - Expecting LIMIT to run before DISTINCT.
LIMIT 10does not take ten rows and then de-duplicate them. It takes ten rows from the de-duplicated, sorted result. To de-duplicate only the first ten rows, put the limit in a subquery. - Pages that overlap or skip rows. This almost always means the
ORDER BYhas ties. Add columns until the sort key is unique. - Using DISTINCT to hide a join problem. If a join multiplies rows and you add
DISTINCTto clean up, you pay for a sort or hash of the whole result and may mask a wrong join condition. Fix the join first. - Applying DISTINCT to everything by habit. It costs work proportional to the result size and can change what your query means.
To de-duplicate only the first ten rows, which is rarely what you want but sometimes does apply, write the limit inside:
SELECT DISTINCT country
FROM (
SELECT country
FROM customers
ORDER BY customer_id
LIMIT 10
) AS first_ten;The inner query takes the first ten customers by customer_id. The outer query then removes duplicate countries among those ten, so you may get fewer than ten rows.
Performance notes
DISTINCT needs to find duplicates, which the database does by sorting or by building a hash table. When the ORDER BY matches the DISTINCT columns, the database can often use one sort for both. With LIMIT, it may stop early only if it can produce rows already in order, for example by reading an index on country. Otherwise it must de-duplicate and sort everything before it can return the first row.
You can check the plan with EXPLAIN. Look for a sort node, a hash aggregate, or a unique node. An index on the columns in SELECT DISTINCT ... ORDER BY ... LIMIT is the most common way to make this cheap.
Summary
DISTINCTruns afterSELECTand beforeORDER BY,OFFSET, andLIMIT.OFFSETandLIMITcount unique rows whenDISTINCTis present.ORDER BYafterDISTINCTcan only use selected columns, so rank by an aggregate withGROUP BYinstead.- Make the sort key unique so pages are stable.
Exercise
A table employees has columns department and hire_date. You write SELECT DISTINCT department FROM employees ORDER BY hire_date DESC LIMIT 3; to get the three departments with the most recent hire. Why is this wrong, and how would you rewrite it?
Show answer
DISTINCT collapses each department to one row, but a department has many hiredate values, so ORDER BY hiredate has no single value to use (PostgreSQL rejects the query). Rewrite it with GROUP BY and an aggregate: SELECT department, MAX(hiredate) AS latesthire FROM employees GROUP BY department ORDER BY latest_hire DESC, department LIMIT 3;
Exercise
The query SELECT DISTINCT country, city FROM customers ORDER BY country LIMIT 10 OFFSET 20 sometimes returns the same (country, city) pair on two different pages when run repeatedly as the user pages. What is the cause, and what is the fix?
Show answer
ORDER BY country alone has many ties, because each country has several cities, so the database may order tied rows differently between runs and page boundaries can shift. Fix it by ordering on every selected column: ORDER BY country, city. That key is unique per row after DISTINCT, so the order is total and pages are stable.