SQL: LIMIT Without ORDER BY Gives Unpredictable Rows
With no ORDER BY, the database can return any rows in any order. Always sort before you limit.
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 rowson 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 10Why it happens
LIMIT keeps the first N rows of the result, but withoutORDER 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 10If 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 10The same rule governs LIMIT … OFFSET … paging: without a stableORDER BY, page 2 can repeat or skip rows it already showed on page 1. Every paged query needs a deterministic sort.
Learn more
Related
Write a first SELECT and read the returned rows.
Return only the columns a report actually needs.
Sort rows and keep the focused top results.
Clause order and the shape of a SELECT query.