Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 19/ 160
01. SQL Foundations & Relational Concepts

Sorting & Limiting Results (ORDER BY, ASC/DESC, LIMIT, OFFSET)

Sort result sets and page with LIMIT/OFFSET while knowing OFFSET pitfalls.

BeginnerORDER BY · LIMIT3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Highest-rated first, unrated lastQuery example
1Input dataStart from the source rows or state that the statement sees.
products
3 rows
products sample rows
idnamepricecategorystock
42SQL Notebook49.5books18
84Mechanical Keyboard150hardware5
11Query Mug12.99gifts33
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  name,3  rating4FROM5  products6ORDER BY7  rating DESC NULLS LAST,8  id;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/8
3OutputInspect the representative rows, affected-row count, plan, or command status.
Products in requested order4 sample rows
Products in requested order
namerating
Trail Shoes4.9
Daypack4.6
Bottle4.1
New ItemNULL

Note: Representative sample showing descending ratings, with NULL placed last and id breaking any rating ties.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Page 3, ten per pageQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  id,3  title4FROM5  posts6ORDER BY7  created_at DESC,8  id DESC9LIMIT10  1011OFFSET12  20;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/12
3OutputInspect the representative rows, affected-row count, plan, or command status.
Posts on page 33 sample rows
Posts on page 3
idtitle
180Window frames
179Index scans
178Query 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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Index the ORDER BY for fast top-N; switch to keyset for deep pages.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1ORDER BY

Choose the sort keys

Pick the column that defines the order and its direction, such as created_at DESC for newest first.

SQL at this step
1ORDER BY2  created_at DESC
What to watch at this step
Default
ASC
Tip: use ← → to move between steps

When 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

ORDER BY … LIMIT n
Best for: Top-N lists and the first page

Strengths: Simple; fast with a matching index.

Watch out: Non-deterministic without a tiebreaker.

LIMIT … OFFSET
Best for: Small tables or shallow pages with page numbers

Strengths: Lets users jump to page N.

Watch out: Slower with every page; shifts when rows are inserted.

Keyset (WHERE after last row)
Best for: Infinite scroll and large tables

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?
Interview tip: Always say "with a tiebreaker" when you write ORDER BY … LIMIT. It's a small habit that shows you've debugged flaky pagination.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Handling NULL Values (IS NULL, IS NOT NULL, Three-Valued Logic)
Next topic
SQL Execution Order vs Logical Writing Order