LIMIT senza ORDER BY (e i pari merito)
Lo incontri quando chiedi «i 5 clienti più recenti» o una pagina di risultati. Senza ORDER BY, LIMIT 5 tiene le
prime cinque righe che il database si trova a leggere; con un ORDER BY che ha pari merito, sceglie arbitrariamente tra
le righe a pari merito.
SELECT customer_id, email, signed_up_on
FROM customers
ORDER BY signed_up_on DESC, customer_id DESC
LIMIT 5;
L'ultima chiave fa da spareggio: nel loro insieme, le colonne dell'ORDER BY devono essere univoche. Per la pagina
successiva, filtra sull'ultima riga vista (signed_up_on < x OR (signed_up_on = x AND customer_id < y)) invece di usare
OFFSET: le righe aggiunte nel frattempo non spostano più le pagine.
La trappola. Su una tabella piccola le righe tornano nell'ordine di caricamento e la query sembra giusta; su
Snowflake, BigQuery o Databricks arrivano da worker paralleli, e domani la stessa query restituisce altre righe. Il
sintomo è un report, una deduplicazione o un test che cambia senza che arrivino dati nuovi; la soluzione, un ORDER BY
che non ammette pari merito.
Sul tuo data warehouse. ORDER BY signed_up_on DESC mette le date mancanti in testa su Postgres e Snowflake (lì
NULL è il valore più grande) e in fondo su BigQuery, Databricks e DuckDB: aggiungi NULLS LAST per avere la stessa
pagina ovunque. Postgres e DuckDB accettano anche il confronto tra righe (signed_up_on, customer_id) < (x, y).
SELECT customer_id, first_name, signed_up_on,
COUNT(*) OVER (PARTITION BY signed_up_on) AS same_day
FROM customers
ORDER BY signed_up_on DESC, customer_id DESC
LIMIT 3;
| customer_id | first_name | signed_up_on | same_day |
|---|---|---|---|
| 51 | Alice | 2025-11-16 | 1 |
| 32 | Nathan | 2025-11-14 | 1 |
| 343 | Maxime | 2025-11-12 | 3 |
SELECT customer_id, first_name, signed_up_on FROM customers WHERE signed_up_on < DATE '2025-11-12' OR (signed_up_on = DATE '2025-11-12' AND customer_id < 343) ORDER BY signed_up_on DESC, customer_id DESC LIMIT 3;
| customer_id | first_name | signed_up_on |
|---|---|---|
| 310 | Chloé | 2025-11-12 |
| 273 | Lucas | 2025-11-12 |
| 203 | Gabriel | 2025-11-08 |