SELECT WHERE ORDER BY Aggregates soon GROUP BY soon
Chapter 3 — Sort Results

ORDER BY: control what comes first.

SELECT picks columns. WHERE filters rows. ORDER BY decides the sequence. Without it, your results arrive in whatever order the database feels like — unpredictable, inconsistent, and useless for ranking.

Chapter 3 30+ min practice 35 Questions Inline Playground
01
Story
02
Anatomy
03
Examples
04
Gotchas
05
Practice
sort_students.sql ▶ Run
5 rows · highest score first
namescore
Raj95
Arjun88
Karan80
Priya72
Simran61
01 4 min read

Results in chaos. ORDER BY fixes that.

You're a data analyst. Your manager asks: "Who are our top 5 students by score?" You run SELECT name, score FROM students; — five rows appear. But not in any meaningful order. Raj (95) is third. Simran (61) is fourth. Your eyes have to do the ranking manually.

Now scale that up. Imagine 10,000 students. Or 500,000 orders. Or 2 million transactions. The database hands them back in the order it stored them — which changes every time someone inserts or deletes a row.

ORDER BY is one line that turns a dump of data into a ranked, meaningful list. It's the difference between raw data and an answer.
Key rule
Without ORDER BY, SQL makes no guarantee about row order. The same query can return rows in completely different sequences on two separate runs. If your report needs a specific order, you must always specify it explicitly.

Compare the same table with and without ORDER BY:

Without ORDER BY — storage order
namescore
Arjun88
Priya72
Raj95
Simran61
Karan80
⚠ Raj (95) is row 3 — not obvious who's top
ORDER BY score DESC
namescore
Raj95
Arjun88
Karan80
Priya72
Simran61
✓ Raj is instantly row 1 — no scanning needed
02 5 min read

ORDER BY: column + direction.

Every ORDER BY has two parts: what to sort by (the column) and which way (ASC or DESC). The direction is optional — if you omit it, SQL defaults to ASC.

Diagram 1 — Full query anatomy
SELECT name, score
Columns
what to show
  
FROM students
Table
where data lives
  
ORDER BY score DESC
Sort
column + direction

When you add WHERE, the clause order must be exactly: FROM → WHERE → ORDER BY → TOP/LIMIT. ORDER BY always comes last. In SQL Server, TOP n goes at the very beginning right after SELECT — not at the end like LIMIT.

SQL Server — full clause order
SELECT TOP 5 name, score    -- TOP n right after SELECT
FROM     students             -- choose table
WHERE    score > 50           -- filter rows (optional)
ORDER BY score DESC;         -- sort (optional)
Playground note: The Try It buttons use LIMIT at the end (SQLite syntax). In SQL Server, write SELECT TOP n ... instead.
Diagram 2 — SQL execution pipeline
STEP 1
FROM
load table
STEP 2
WHERE
filter rows
STEP 3
SELECT
pick columns
STEP 4
ORDER BY
sort rows
STEP 5
TOP / LIMIT
cap output
You write SELECT first, but SQL runs ORDER BY almost last — after all filtering and column selection. This means ORDER BY can reference columns not in your SELECT list (it sees the full row). TOP/LIMIT runs after ORDER BY, so "top 3" always means top 3 of the sorted list. In SQL Server, write SELECT TOP 3 ...; in SQLite/MySQL, write LIMIT 3 at the end.
03 8 min read

ASC, DESC, and everything in between.

ASC vs DESC — side by side

ORDER BY score ASC  (default)
#namescore
1Simran61
2Priya72
3Karan80
4Arjun88
5Raj95
Smallest value first → largest last
ORDER BY score DESC
#namescore
1Raj95
2Arjun88
3Karan80
4Priya72
5Simran61
Largest value first → smallest last

Text columns sort alphabetically (A→Z for ASC, Z→A for DESC). Dates sort earliest-first for ASC.

Multi-column sort: tie-breaking

ORDER BY city ASC, score DESC
Primary sort: city A→Z
citynamescorenote
ChennaiKaran80only 1 in Chennai
DelhiArjun88← higher score wins
DelhiSimran61← secondary sort kicks in
MumbaiPriya72only 1 in Mumbai
PuneRaj95only 1 in Pune
The first column is the primary key — rows are grouped by city first. The second column only decides order within rows that share the same city. Delhi has two students, so score DESC puts Arjun (88) before Simran (61).

Live examples — try them in the playground

E01 Basic DESC — highest first
Sort all students by score, highest to lowest.
SQL
SELECT * FROM students ORDER BY score DESC;
Result (5 rows)
idnamecityscore
3RajPune95
1ArjunDelhi88
5KaranChennai80
2PriyaMumbai72
4SimranDelhi61
E02 Basic ASC — lowest first (default)
Select only name and score, sorted lowest score first.
SQL
SELECT name, score FROM students ORDER BY score ASC;
Result (5 rows)
namescore
Simran61
Priya72
Karan80
Arjun88
Raj95
E03 Multi-column — city A→Z, then score high→low
Sort by city alphabetically. Within each city, put the highest scorer first.
SQL
SELECT name, city, score FROM students
ORDER BY city ASC, score DESC;
E04 Top-N pattern — ORDER BY + TOP (SQL Server)
Get only the top 3 highest-scoring students. In SQL Server, TOP n goes right after SELECT — before the column list. This Top-N pattern appears in almost every real-world query.
SQL Server
SELECT TOP 3 name, score
FROM students
ORDER BY score DESC;
Result (3 rows)
namescore
Raj95
Arjun88
Karan80
SQL Server — Paging with OFFSET-FETCH

For skipping rows and returning a "page" of results, SQL Server uses OFFSET … ROWS FETCH NEXT … ROWS ONLY — not LIMIT. ORDER BY is required when using OFFSET-FETCH.

SQL Server — page 2 of results (rows 6–10)
SELECT name, score
FROM students
ORDER BY score DESC
OFFSET 5 ROWS FETCH NEXT 5 ROWS ONLY;
OFFSET 5 ROWS — skip the first 5 rows  ·  FETCH NEXT 5 ROWS ONLY — return the next 5. Use OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY for page 1.
E05 Expression sort — ORDER BY LEN(name) — SQL Server
You can use any expression inside ORDER BY — not just column names. Sort students from shortest name to longest. In SQL Server, use LEN() for character count; this playground (SQLite) uses LENGTH().
SQL
SELECT name FROM students
ORDER BY LEN(name) ASC;
E06 WHERE + ORDER BY combined
Filter Delhi students first, then sort by score. WHERE always comes before ORDER BY.
SQL
SELECT name, score FROM students
WHERE  city = 'Delhi'
ORDER BY score DESC;
Result (2 rows)
namescore
Arjun88
Simran61
04 6 min read

Four things that trip people up.

Edge case reference

SituationWorks?Notes
ORDER BY a column not in SELECT ✓ Yes SQL sees the full row when sorting — the column doesn't need to appear in your output
ORDER BY 2 (column position) ✓ Yes Refers to the 2nd column in the SELECT list — useful shorthand, but reduces readability
ORDER BY LENGTH(name) (expressions) ✓ Yes Any valid expression works — functions, arithmetic, string ops
ORDER BY an alias defined in SELECT ✓ Yes SELECT score AS total ... ORDER BY total — works in SQL Server and most modern databases
NULL values in ASC sort ⚠ NULLs first SQL Server treats NULL as less than any non-NULL — NULLs appear at the top of ASC, bottom of DESC

NULL behavior in ORDER BY

If your table has NULL scores, their position in the sort depends on the direction. SQL Server (and SQLite) treat NULL as lower than any real value:

ORDER BY score ASC
NULLfirst ↑
NULL
61
72
80
88
95
ORDER BY score DESC
95first ↑
88
80
72
61
NULLlast ↓
NULL

Common mistakes

Missing BY keyword
ORDER name is a syntax error. The keyword is always two words: ORDER BY.
DSC instead of DESC
DSC is not valid SQL. The abbreviation for descending is always DESC (four letters).
SORT BY instead of ORDER BY
SQL does not have a SORT BY clause. It's always ORDER BY. SORT BY exists in Hive SQL, not standard SQL.
ORDER BY before WHERE
Writing ORDER BY score WHERE score > 70 is a syntax error. WHERE always comes before ORDER BY.
LIMIT before DESC
ORDER BY score LIMIT 3 DESC is wrong. Direction goes right after the column: ORDER BY score DESC LIMIT 3.
Multi-column needs a comma
ORDER BY city score is ambiguous. Always use a comma: ORDER BY city ASC, score DESC.
ASC is optional but explicit is better
ORDER BY score and ORDER BY score ASC are identical. Writing ASC explicitly makes your intent clear to anyone reading the query.
Each column can have its own direction
ORDER BY city ASC, score DESC is valid. Each column in a multi-sort can independently be ASC or DESC.
Ties are non-deterministic — always add a tiebreaker
When two rows share the same sort key, SQL Server does not guarantee their order. Run the same query twice and you may get different sequences. Fix: add a unique column as the final sort key — ORDER BY score DESC, id ASC — so every row has a unique sort position.
Custom sort order — use CASE WHEN inside ORDER BY
To sort by a custom priority (e.g., Delhi first, then others): ORDER BY CASE WHEN city='Delhi' THEN 0 ELSE 1 END ASC, score DESC. No multiple queries or client-side sorting needed.

Quick reference

ORDER BY Everything you now know
  • Default is ASCORDER BY score and ORDER BY score ASC are identical. If you need descending, always write DESC explicitly.ORDER BY score DESC
  • Always after WHERE — the fixed clause order is FROM → WHERE → ORDER BY. Putting ORDER BY before WHERE is a syntax error. In SQL Server, TOP n goes at the start: SELECT TOP n ... ORDER BY col.WHERE score > 70 ORDER BY score DESC
  • Multi-column with comma — first column is primary sort; subsequent columns break ties within equal values.ORDER BY city ASC, score DESC
  • Top-N pattern — SQL Server: SELECT TOP n ... ORDER BY col. TOP runs after ORDER BY is applied, so you always get the correctly ranked top/bottom.SELECT TOP 3 name, score FROM students ORDER BY score DESC
  • Expressions work — any expression is valid: LENGTH(name), price * stock, aliases defined in SELECT.ORDER BY LENGTH(name) ASC
  • NULLs sort first in ASC, last in DESC — true in SQL Server and SQLite. NULL is treated as lower than any real value. Be aware if your data has missing values.
04b

ORDER BY quick reference — patterns and performance

All ORDER BY patterns at a glance. The dialect table shows SQL Server's TOP/OFFSET-FETCH vs other databases.

ORDER BY Cheat Sheet
Basic ascending (default)
SELECT name, score FROM students ORDER BY score;
ASC is the default. Writing it is optional but explicit is clearer.
Descending
SELECT name, score FROM students ORDER BY score DESC;
Highest value first. Always write DESC explicitly.
Multi-column with tiebreaker
SELECT name, city, score FROM students ORDER BY city ASC, score DESC;
Primary sort: city. Tiebreaker: score. Each column has its own direction.
Top-N — SQL Server
SELECT TOP 3 name, score FROM students ORDER BY score DESC;
TOP goes right after SELECT. Always combine with ORDER BY for meaningful results.
Paging — OFFSET-FETCH (SQL Server)
SELECT name, score FROM students ORDER BY score DESC OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY;
Skip first 10, return next 10. ORDER BY is required.
Sort by expression
SELECT name FROM students ORDER BY LEN(name) ASC;
Any expression is valid. LEN() is SQL Server; LENGTH() is SQLite/PostgreSQL.
Sort by alias
SELECT name, score * 2 AS bonus FROM students ORDER BY bonus DESC;
SQL Server allows ORDER BY to reference SELECT aliases.
Custom sort (CASE in ORDER BY)
SELECT name, city FROM students ORDER BY CASE WHEN city='Delhi' THEN 0 ELSE 1 END ASC, score DESC;
Assign numeric priorities per row. Delhi rows get 0 (first), others 1.
Deterministic sort (add tiebreaker)
SELECT name, score FROM students ORDER BY score DESC, id ASC;
Ties are non-deterministic. Always add a unique column (id) as final tiebreaker.
WHERE + ORDER BY combined
SELECT name, score FROM students WHERE score > 70 ORDER BY score DESC;
WHERE always before ORDER BY. Clause order: FROM → WHERE → ORDER BY.
Performance Tips
ORDER BY indexed col
Fastest
When the sort column has an index, SQL Server reads rows in already-sorted order — no sort operation needed.
Put an index on columns you sort most often: date, status, score.
ORDER BY expression
Sort cost
ORDER BY LEN(name) or ORDER BY price * qty can't use a plain index — SQL must compute per row, then sort.
For repeated expression sorts, use a computed column with an index.
TOP 1 with index
Near-instant
SQL Server stops scanning as soon as it finds the top row when the sort column is indexed.
Common pattern: SELECT TOP 1 * FROM orders ORDER BY order_date DESC
OFFSET-FETCH
Better than ROW_NUMBER
OFFSET-FETCH is optimized by SQL Server's query engine. Prefer it over ROW_NUMBER() workarounds for simple paging.
Page 1 = OFFSET 0, page 2 = OFFSET 10, page N = OFFSET (N-1)*pageSize.
No ORDER BY = no guarantee
Danger zone
Without ORDER BY, SQL Server returns rows in whatever order is most convenient — which can change between runs.
Never rely on "default" row order. Always use ORDER BY when sequence matters.
DISTINCT + ORDER BY
Extra cost
DISTINCT requires de-duplication (sort/hash), then ORDER BY sorts again — two operations on large tables.
Filter duplicates upstream when possible rather than at query time.
SQL Dialect Comparison — ORDER BY

How row limiting and paging differs across databases.

FeatureSQL ServerMySQL / MariaDBPostgreSQLSQLite
Top-N rowsSELECT TOP n ...LIMIT nLIMIT nLIMIT n
Paging (skip N)ORDER BY col OFFSET n ROWS FETCH NEXT n ROWS ONLYLIMIT n OFFSET nLIMIT n OFFSET nLIMIT n OFFSET n
NULL sort (ASC)✓ NULLs first (lowest)⚡ NULLs last⚡ NULLs last (use NULLS FIRST)✓ NULLs first
NULLS FIRST/LAST✗ Not supported — use CASE in ORDER BY✗ Not supportedORDER BY col NULLS LAST✗ Not supported
ORDER BY alias✓ Supported✓ Supported✓ Supported✓ Supported
ORDER BY positionORDER BY 2✓ Supported✓ Supported✓ Supported
CASE in ORDER BY✓ Supported✓ Supported✓ Supported✓ Supported
✓ fully supported  ·  ⚡ alternative syntax  ·  ✗ not natively supported

Practice — 0 / 35 done

Work through MCQ → Fix-It → Write in order. Use the playground on every Write question.
10 MCQ — concept checks 10 Fix-It — spot the bug 15 Write — build from scratch
0 / 35 Start with Q01
Type
Difficulty
38 questions
No questions match your filter.
06 5 min read

8 questions interviewers ask about ORDER BY.

Click any card to reveal the answer. These surface the why behind the syntax.

Concept Trap Pattern Advanced

Trap If you don't use ORDER BY, can you rely on any default row order?
No. Without ORDER BY, SQL Server returns rows in whatever order it finds most efficient — which can change between runs depending on query plan, index state, and parallelism.
-- No ORDER BY: order is unpredictable SELECT name, score FROM students; -- Safe: always specify the order you need SELECT name, score FROM students ORDER BY score DESC;
Common trap: "It always came back in id order." That's coincidence — typically the physical storage order on a small table. After updates, deletes, and page splits, row order is truly unpredictable.
Concept What is a non-deterministic sort, and how do you fix it?
A sort is non-deterministic when two rows share the same sort key — SQL Server doesn't guarantee which one comes first. Fix: add a unique tiebreaker column as the final sort key.
-- Non-deterministic: if two students have score 80, they may swap SELECT name, score FROM students ORDER BY score DESC; -- Deterministic: id is unique, so every row has a distinct position SELECT name, score FROM students ORDER BY score DESC, id ASC;
Best practice: Always end your ORDER BY with a unique column (typically the primary key) for stable, reproducible results — especially in pagination.
Pattern What is the SQL Server syntax for pagination (skipping N rows)?
Use OFFSET n ROWS FETCH NEXT n ROWS ONLY after ORDER BY. ORDER BY is required — you can't use OFFSET-FETCH without it.
-- Page 1 (rows 1-10) SELECT name, score FROM students ORDER BY score DESC OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY; -- Page 2 (rows 11-20) SELECT name, score FROM students ORDER BY score DESC OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY;
Not LIMIT/OFFSET: SQL Server does not support LIMIT. Always use the full OFFSET n ROWS FETCH NEXT n ROWS ONLY syntax.
Concept Where do NULLs appear when you ORDER BY a nullable column in SQL Server?
SQL Server treats NULL as lower than any non-NULL value. In ASC order NULLs appear first; in DESC order NULLs appear last.
-- ASC: NULLs appear at the top (first) SELECT name, score FROM students ORDER BY score ASC; -- DESC: NULLs appear at the bottom (last) SELECT name, score FROM students ORDER BY score DESC;
PostgreSQL difference: PostgreSQL sorts NULLs last in ASC by default and supports ORDER BY score ASC NULLS FIRST. SQL Server does not support NULLS FIRST/LAST — use CASE WHEN score IS NULL THEN 1 ELSE 0 END as a workaround.
Advanced Can you use ORDER BY inside a subquery in SQL Server?
Not directly. ORDER BY in a subquery requires TOP or OFFSET-FETCH to be present. Without them it's a syntax error.
-- ERROR: ORDER BY in subquery without TOP SELECT * FROM ( SELECT name, score FROM students ORDER BY score DESC -- Error! ) AS ranked; -- VALID: add TOP to enable ORDER BY SELECT * FROM ( SELECT TOP 100 PERCENT name, score FROM students ORDER BY score DESC ) AS ranked;
Important: SQL Server does NOT guarantee the subquery result is sorted after the outer query processes it. For reliable sorted output, always use ORDER BY on the outermost query.
Pattern How do you sort NULL values last in SQL Server when ordering ASC?
SQL Server doesn't support NULLS LAST. Use a CASE expression to assign NULLs a high sort priority, pushing them to the end.
-- Push NULLs to the end in ASC order SELECT name, score FROM students ORDER BY CASE WHEN score IS NULL THEN 1 ELSE 0 END ASC, score ASC;
Memory hook: CASE in ORDER BY = custom priority lane. Give NULLs the lane you don't want them in by default.
Trap What is the difference between SELECT TOP 3 without ORDER BY and with ORDER BY?
SELECT TOP 3 without ORDER BY returns 3 arbitrary rows. With ORDER BY, TOP 3 returns the actual top 3 by the specified sort.
-- Returns 3 RANDOM rows (no guaranteed meaning) SELECT TOP 3 name, score FROM students; -- Returns the 3 HIGHEST scoring students SELECT TOP 3 name, score FROM students ORDER BY score DESC;
Interview trap: "Which students have the top 3 scores?" — you must include ORDER BY. Without it, TOP is meaningless for data analysis.
Advanced How does an index on a sorted column improve ORDER BY performance?
A b-tree index stores values in sorted order. When you ORDER BY an indexed column, SQL Server reads rows directly from the index in order — skipping the sort operation entirely.
-- Without index on score: full scan + Sort operator in execution plan -- With index on score: index scan in sorted order (no Sort operator) SELECT name, score FROM students ORDER BY score DESC;
Covering index: If the index includes all selected columns, SQL Server satisfies the query entirely from the index — no table access at all. This is the fastest possible path.
Practical rule: For frequent WHERE + ORDER BY on same column, a composite index on (filter_col, sort_col) can cover both operations.
Up Next
Aggregates: COUNT, SUM, AVG, MAX, MIN
Learn to calculate totals, averages, and statistics across rows of data.
Aggregates SOON
Question completed
0%