SQL · Module 4 · Lesson 61 min read

ORDER BY, LIMIT & OFFSET

ORDER BY

SQL
SELECT … FROM … ORDER BY column [ASC | DESC];
  • ASC (ascending) is the default: A→Z, 1→9, oldest→newest
  • DESC: Z→A, 9→1, newest→oldest
  • ⚠️ Without ORDER BY, row order is NOT guaranteed — never rely on "insertion order"

Multiple columns

ORDER BY city ASC, amount DESC – sort by city, then by amount within each city

Other ways to sort

  • By an alias: ORDER BY total DESC (ORDER BY runs after SELECT, so aliases work)
  • By an expression: ORDER BY length(title)
  • By position: ORDER BY 2 (works, but avoid it — it's fragile)
  • NULL placement: NULLS FIRST / NULLS LAST

LIMIT – how many rows

LIMIT 5 → the first 5 rows (after sorting). Always combine LIMIT with ORDER BY, or you get random rows.

Standard SQL equivalent: FETCH FIRST 5 ROWS ONLY (WITH TIES includes rows tied with the last one).

OFFSET – skip rows (pagination)

LIMIT 10 OFFSET 20 → rows 21–30 (page 3 with 10 per page)

  • Page formula: OFFSET (page - 1) * page_size
  • ⚠️ Large OFFSETs are slow (the database still reads and discards the skipped rows) and can show duplicates if data changes between pages. For big tables use keyset pagination: WHERE id < last_seen_id ORDER BY id DESC LIMIT 10 (Unit 11).

Make the order deterministic

If values can tie (same date), add a unique column as a tie-breaker: ORDER BY spent_on DESC, id DESC. Otherwise pages may overlap.

Example

SQL
-- Top 5 biggest expenses
SELECT title, amount FROM expenses
ORDER BY amount DESC
LIMIT 5;
-- Paragliding 8500, Flight to Pokhara 7800, Running shoes 6500, Monthly groceries 5200, Jacket 4200

-- Newest first, with a tie-breaker
SELECT id, title, spent_on FROM expenses
ORDER BY spent_on DESC, id DESC
LIMIT 3;

-- Multiple sort columns: by city A→Z, then budget high→low
SELECT name, city, monthly_budget FROM users
ORDER BY city ASC NULLS LAST, monthly_budget DESC;

-- Sort by an alias
SELECT title, amount * 1.13 AS with_vat FROM expenses
ORDER BY with_vat DESC
LIMIT 3;

-- Pagination: page 2, 5 rows per page
SELECT id, title FROM expenses
ORDER BY id
LIMIT 5 OFFSET 5;          -- ids 6..10

-- Standard SQL + WITH TIES (includes everyone tied with 5th place)
SELECT title, amount FROM expenses
ORDER BY amount DESC
FETCH FIRST 7 ROWS WITH TIES;   -- may return more than 7 rows if amounts tie