SQL Dojo
Pitfall

LIMIT without ORDER BY (and ties)

LIMIT without a complete ORDER BY returns some rows, not the ones you mean, and they can change between runs: add a tiebreaker, page with a key.

You meet it when you ask for "the 5 newest customers" or a page of results. Without ORDER BY, LIMIT 5 keeps the first five rows the database happens to read; with an ORDER BY that has ties, it picks among the tied rows.

SELECT customer_id, email, signed_up_on
FROM customers
ORDER BY signed_up_on DESC, customer_id DESC
LIMIT 5;

The last key breaks the ties: together, the columns of the ORDER BY must be unique. For the next page, filter on the last row seen (signed_up_on < x OR (signed_up_on = x AND customer_id < y)) rather than OFFSET: rows added meanwhile no longer shift the pages.

The trap. On a small table the rows come back in the order they were loaded, and the query looks right; on Snowflake, BigQuery or Databricks they arrive from parallel workers, and tomorrow the same query returns other rows. The symptom is a report, a dedupe or a test that changes with no new data; the fix, an ORDER BY that cannot tie.

On your warehouse. ORDER BY signed_up_on DESC puts the missing dates first on Postgres and Snowflake (NULLs sort as the largest value) and last on BigQuery, Databricks and DuckDB: add NULLS LAST to get the same page everywhere. Postgres and DuckDB also accept the row value (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_idfirst_namesigned_up_onsame_day
51Alice2025-11-161
32Nathan2025-11-141
343Maxime2025-11-123
Try it in Randori
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_idfirst_namesigned_up_on
310Chloé2025-11-12
273Lucas2025-11-12
203Gabriel2025-11-08
Try it in Randori