QA Interview Hub · Knowledge base · Quizzes · Українська

SQL › SELECT and filtering

How do ORDER BY and LIMIT work?

ORDER BY is the only thing that defines row order: without it a table is a set, and LIMIT 1 returns an arbitrary row. LIMIT runs after sorting, and rows with an equal key come in arbitrary order, so a unique key goes at the end of the sort. NULL is placed differently (PostgreSQL treats it as greater than everything, MySQL as smaller), so its position is set explicitly.

SQL · SELECT and WHERE

A test takes the first record and fails once every few runs. Same data, same code. Where does the randomness come from?

An autotest checks "the user's latest transaction" and fails about once in ten runs. The database has the same data set and the query did not change. The cause is simple and sly: the query does not define an order and the database does not have to return rows the same way each time. This lesson covers ORDER BY and LIMIT: what they guarantee and what they do not.

How it works and why. In the relational model a table is a set of rows, not a list. The order in which SELECT returns them without ORDER BY depends on the execution plan, the physical layout and parallel scanning, and can change after an UPDATE or after the planner chooses another index. The standard promises nothing. ORDER BY sorts by one or several columns (ASC by default, DESC), and LIMIT (and OFFSET) runs after sorting: the first n rows of the sorted set are taken. So "LIMIT 1 without ORDER BY" means "one random row".

The second half of the guarantee is subtler: sorting defines an order only for different key values. Rows with the same value (two transactions with the same created_at) stand in an arbitrary order, and LIMIT 1 may take either of them. That is the source of the random failures. It is reliable only when the end of the sort list has a unique key.

-- no ORDER BY: the "first" transaction can be any
SELECT id, amount FROM transactions LIMIT 1;

-- ORDER BY exists but created_at repeats: the order of equal rows is undefined
SELECT id, amount FROM transactions
ORDER BY created_at DESC LIMIT 1;

How much a query guarantees

Unstable

LIMIT 1 without ORDER BY, or with a non-unique key

Any row among those with a matching key. The test passes until the execution plan changes and then fails.

Stable

ORDER BY created_at DESC, id DESC

The unique id settles ties. The same data set always gives the same result.

Figure 1. For a "first record" test the order must be fully defined, otherwise the result is random.

Example: NULL in sorting. The second cause of instability between environments: where NULLs are placed. In PostgreSQL and Oracle NULL counts as larger than every value, so with ASC it comes last and with DESC first. In MySQL, SQL Server and SQLite it is the opposite: NULL is smaller than everything. A test that worked on PostgreSQL will change its order on another database.

The same ASC, different databases

PostgreSQL
idbalance
210
150
3NULL
MySQL
idbalance
3NULL
210
150
Figure 2. The same data and the same ORDER BY balance ASC. Set the NULL position explicitly: NULLS FIRST or NULLS LAST where it is supported.

The fixed query:

-- a unique second key makes the order stable
SELECT id, amount
FROM transactions
ORDER BY created_at DESC, id DESC
LIMIT 10;

-- NULL explicitly: PostgreSQL, Oracle, SQLite 3.30+
SELECT id, balance FROM accounts ORDER BY balance ASC NULLS LAST;
-- MySQL: ORDER BY balance IS NULL, balance
-- SQL Server: ORDER BY CASE WHEN balance IS NULL
--   THEN 1 ELSE 0 END, balance
DatabaseRow limitNULL with ASC
PostgreSQLLIMIT, FETCH FIRSTlast
MySQLLIMITfirst
SQL ServerTOP, OFFSET … FETCHfirst
OracleFETCH FIRST (12c+)last
SQLiteLIMITfirst

Limits and alternatives. Text sorting depends on the collation: the order of the letters "a", "B", "Z" and letters with diacritics differs between settings. And if a number is stored as text, '10' comes before '9': the sort is lexicographic. PostgreSQL's LIMIT has the standard synonym FETCH FIRST n ROWS ONLY, and FETCH FIRST n ROWS WITH TIES also returns the rows equal to the last one by key. In SQL Server OFFSET … FETCH requires ORDER BY. OFFSET k is expensive for large values: the database still walks through and discards k rows, and if new data appears between queries the pages shift and give repeats or gaps. For large lists where stability matters, keyset pagination is used: a condition on the value of the last seen row instead of OFFSET.

-- the next page after the last seen row (keyset)
SELECT id, created_at
FROM transactions
WHERE (created_at, id) < ('2026-09-15 10:05', 4021)
ORDER BY created_at DESC, id DESC
LIMIT 10;

Common mistakes.

  • LIMIT without ORDER BY: a random "first" row and unstable tests.
  • Sorting by a non-unique key without an extra one: equal rows swap places.
  • Relying on the NULL position without checking the database.
  • Sorting a number stored as text.
  • A deep OFFSET on large tables or on lists that change.

Check yourself

Why can a test that takes LIMIT 1 with ORDER BY created_at DESC fail once every few runs?

Answer

Two transactions may have the same created_at, and the database returns them in an arbitrary order. You need a unique second key, for example ORDER BY created_at DESC, id DESC.

Where will the row with NULL be in ORDER BY balance ASC in PostgreSQL and MySQL?

Answer

Last in PostgreSQL (NULL counts as the largest), first in MySQL (NULL is the smallest). To not depend on the database you need an explicit NULLS FIRST or NULLS LAST or an expression with IS NULL.

Why does ORDER BY name return '10' before '9'?

Answer

The column is text and the sort is lexicographic: characters are compared left to right and '1' is less than '9'. Store the number as a numeric type or cast it in the query.

In an interview. Junior: ORDER BY sorts ascending or descending and LIMIT caps the row count. Without ORDER BY the order is not guaranteed, so LIMIT without sorting gives arbitrary rows and unstable tests. Middle/Senior: A table is a set and only ORDER BY gives an order, while equal keys come in an arbitrary order, so I put a unique key such as id at the end of the sort. NULL sorts differently depending on the database: in PostgreSQL it is larger than everything and in MySQL smaller, so I set the position explicitly. For large lists I prefer keyset pagination, because a deep OFFSET is slow and shifts pages.

More articles in this chapter