Sorting & Limiting Results (ORDER BY, ASC/DESC, LIMIT, OFFSET)
Sort result sets and page with LIMIT/OFFSET while knowing OFFSET pitfalls.
In plain words
ORDER BY puts rows in order; LIMIT keeps only the first few. Add a second sort column so ties always come out the same way.
Think of it like…
Sorting exam papers by score and handing back the top ten: if two papers have the same score, you need a second rule (alphabetical by name) or the tenth and eleventh places could swap every time you sort.
Where you’ve seen it
The 10 newest products: SELECT id, name, created_at FROM products ORDER BY created_at DESC, id DESC LIMIT 10;. The id tiebreaker keeps the order stable when several products were created in the same second.
Words you’ll hear
- ASC / DESC
- Ascending (default) or descending order for each sort key.
- Multiple sort keys
- ORDER BY a, b sorts by a, then by b within equal a.
- NULLS FIRST / LAST
- Where NULLs go in the order (PostgreSQL, Oracle, SQLite).
- LIMIT / OFFSET
- How many rows to return, and how many to skip first.
Visual diagram
Theory & example queries
Sorting reliably
ORDER BY accepts columns, expressions, SELECT aliases or column positions (ORDER BY 2). Each key can have its own direction: ORDER BY country ASC, revenue DESC. When sort values tie, their relative order is undefined, so a LIMIT can return different rows on different runs. Add a unique column, usually the primary key, as the last sort key.
NULL placement differs: PostgreSQL treats NULL as larger than any value (last in ASC, first in DESC), MySQL and SQL Server treat it as smaller (first in ASC). PostgreSQL and Oracle let you say NULLS LAST explicitly; in MySQL use ORDER BY col IS NULL, col.
| id | name | price | category | stock |
|---|---|---|---|---|
| 42 | SQL Notebook | 49.5 | books | 18 |
| 84 | Mechanical Keyboard | 150 | hardware | 5 |
| 11 | Query Mug | 12.99 | gifts | 33 |
SELECT name, ratingFROM productsORDER BY rating DESC NULLS LAST, id;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Products in requested order4 sample rows
| name | rating |
|---|---|
| Trail Shoes | 4.9 |
| Daypack | 4.6 |
| Bottle | 4.1 |
| New Item | NULL |
Note: Representative sample showing descending ratings, with NULL placed last and id breaking any rating ties.
Key takeaway: Add a unique tiebreaker, and state where NULLs go.
LIMIT, OFFSET and performance
LIMIT 10 keeps the first 10 rows of the sorted result; LIMIT 10 OFFSET 20 skips 20 first, giving page 3. MySQL also accepts LIMIT 20, 10; SQL Server uses TOP 10 or OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY. LIMIT without ORDER BY is fine for a quick look at data, but never for results that matter.
With an index matching the ORDER BY (for example on created_at), the database can read just the first rows of the index instead of sorting the whole table, so top-N queries stay fast. OFFSET still reads and discards every skipped row, which makes deep pages slow; keyset pagination (WHERE (created_at, id) < (…)) fixes that.
SELECT id, titleFROM postsORDER BY created_at DESC, id DESCLIMIT 10OFFSET 20;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Posts on page 33 sample rows
| id | title |
|---|---|
| 180 | Window frames |
| 179 | Index scans |
| 178 | Query plans |
Note: Assumes the newest posts sorted by created_at and id produce these rows at offset 20; the page may contain up to 10 rows.
Key takeaway: Index the ORDER BY for fast top-N; switch to keyset for deep pages.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Choose the sort keys
Pick the column that defines the order and its direction, such as created_at DESC for newest first.
ORDER BY created_at DESCWhen to use it & trade-offs
What it is
ORDER BY sorts the result by one or more columns or expressions, ascending (ASC, the default) or descending (DESC). LIMIT n returns only the first n rows and OFFSET m skips m rows first. SQL Server uses TOP n or OFFSET … FETCH. Without ORDER BY, the database may return rows in any order, so LIMIT alone returns arbitrary rows.
Why it matters: "Top 10" lists, latest-first feeds and pagination are everywhere. The traps are ties that make results change between runs, NULLs sorting first or last depending on the database, and OFFSET getting slow on deep pages. Each is a common interview follow-up.
When to reach for it
- Newest-first feeds and lists
- Top-N reports
- Paginated API endpoints
When to avoid or be careful
- LIMIT without ORDER BY for anything users see
- Sorting on non-unique columns without a tiebreaker
- Deep OFFSET pagination on large tables
Top-N and paging approaches
Strengths: Simple; fast with a matching index.
Watch out: Non-deterministic without a tiebreaker.
Strengths: Lets users jump to page N.
Watch out: Slower with every page; shifts when rows are inserted.
Strengths: Constant cost per page; stable.
Watch out: No jumping to arbitrary pages.
Interview signals & numbers to know
When this topic comes up
- “Top 10 products”
- “Latest orders first”
- “Results change order between page loads”
- Pagination
- NULLs at the top of a sorted list
Benchmarks & rules of thumb
- ASC
- default direction
- NULLS LAST
- PostgreSQL default for ASC
- OFFSET n
- rows read and thrown away
Common mistakes & follow-ups
Common interview mistakes
- Using LIMIT 10 without ORDER BY and getting a different 10 rows after a restart or VACUUM.
- Sorting only by created_at, so products created in the same second swap places between pages.
- Sorting ratings DESC in PostgreSQL and finding all the NULL ratings at the top.
Likely interviewer follow-ups
- Why can ORDER BY … LIMIT return different rows on different runs?
- Where do NULLs appear in ORDER BY … DESC in PostgreSQL?
- Why is OFFSET pagination slow on later pages?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Sorting & Limiting Results (ORDER BY, ASC/DESC, LIMIT, OFFSET) with hands-on SQL practice and interview Q&A.