SQL: LIMIT Without ORDER BY Gives Unpredictable Rows
With no ORDER BY, SQL does not guarantee which rows come first. Sort before LIMIT when the specific rows or their order matter.
The symptom
You want the "top 10" or a quick sample, so you add LIMIT 10.
It looks fine until the same query returns different rows
on another run, on a different database, or after the table is updated. Your
"top" report isn't actually the top of anything.
select product_name, price
from products
limit 10 Why it happens
LIMIT keeps the first N rows of the result, but without
ORDER BY, SQL does not promise any particular
order. The database returns rows in whatever order is convenient (storage
order, parallel scan order, index order), and that can change between runs,
versions, and engines. LIMIT then slices that undefined order,
so which rows you get is essentially arbitrary.
The fix
Add an ORDER BY that makes "first" mean something. For a real
top-N, order by the metric; then LIMIT is meaningful and
stable.
select product_name, price
from products
order by price desc
limit 10
If ties matter, add a tiebreaker column so the order is fully deterministic;
otherwise rows with equal price can still swap places.
select product_name, price
from products
order by price desc, product_name
limit 10
The same rule governs LIMIT … OFFSET … paging: without a stable
ORDER BY, page 2 can repeat or skip rows it already showed on
page 1. Stable offset-based pagination needs a deterministic sort.
Learn more
Related
Write a first SELECT and read the returned rows.
Clause order and the shape of a SELECT query.
SELECT, WHERE, ORDER BY, and LIMIT at a glance.
Practice ranking, running totals, and top row per group.
Filter window results in a CTE or with QUALIFY.
Return only the columns a report needs, each value once.