Sorting and Paging

A query result without ORDER BY has no defined order. The same query can return rows in a different order when the execution plan or the data changes. When you need an order, always use ORDER BY.

Sorting by multiple keys

When you list keys separated by commas, rows with equal earlier keys are sorted by the next key. Each key takes its own ASC (ascending, the default) or DESC (descending).

Grade ascending, join date descending

SELECT cust_id, grade, join_dt
FROM customers
WHERE cust_id <= 30
ORDER BY grade, join_dt DESC

Sorting by expressions and aliases

ORDER BY accepts not only columns but also expressions and aliases from SELECT. This is because SELECT is evaluated before ORDER BY.

Grades in a fixed order

SELECT cust_id, grade,
       CASE grade WHEN 'VIP' THEN 1 WHEN 'GOLD' THEN 2 ELSE 3 END AS grade_rank
FROM customers
WHERE cust_id BETWEEN 90 AND 110
ORDER BY grade_rank, cust_id

Where do NULLs go?

DBNULLs in ascending orderNULLS FIRST / NULLS LAST
OracleLastSupported
PostgreSQLLastSupported
SQL ServerFirstNot supported

Oracle, PostgreSQL · NULLs first

SELECT cust_id, NULLIF(region, 'SEOUL') AS region
FROM customers
WHERE cust_id <= 10
ORDER BY region NULLS FIRST, cust_id

SQL Server · NULLs last

SELECT cust_id, NULLIF(region, 'SEOUL') AS region
FROM customers
WHERE cust_id <= 10
ORDER BY CASE WHEN NULLIF(region, 'SEOUL') IS NULL THEN 1 ELSE 0 END, region, cust_id

In SQL Server, make the NULL test the first sort key with CASE to set the position. This method works in all three DBs.

OFFSET and FETCH: paging

The standard syntax is OFFSET n ROWS FETCH NEXT m ROWS ONLY. The same statement runs on Oracle 12c+, PostgreSQL, and SQL Server 2012+. SQL Server requires an ORDER BY.

Page 3 (10 rows per page)

SELECT cust_id, cust_nm, grade
FROM customers
ORDER BY cust_id
OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY
DBOther syntax with the same meaning
PostgreSQLLIMIT 10 OFFSET 20
SQL ServerFirst page only: SELECT TOP (10) …
Oracle 11g and earlierAn inline view using ROWNUM

Pages are correct only with a unique sort key

Rows with equal sort keys have no defined order among themselves. If the sort key has duplicates, a row can appear on two pages at a page boundary, or on none. Add the primary key as the last sort key.

Sort by join date + primary key

SELECT cust_id, join_dt
FROM customers
ORDER BY join_dt DESC, cust_id
OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY

join_dt has 1,800 distinct values spread over 100,000 customers, so many dates repeat. cust_id sets the order within the same date.

TIP With a large OFFSET, the DB reads and discards all rows of the earlier pages. For deep pages, keyset paging, which continues from the last key seen, is faster (tuning scenario 3).