ORDER BY
ORDER BY sorts the result.
Introduction
ORDER BY sorts the result. By default ascending; use DESC for descending. You can sort by multiple columns and by computed expressions.
Learning objective: Apply ORDER BY correctly in a TechLearningPRO production database — with clear query intent, safe defaults, and failure modes you can explain in review.
Treat every example as production-shaped SQL: explicit column lists, deterministic predicates, and indexes that match the access path. Prefer PostgreSQL dialect notes when dialects diverge; call out MySQL differences when they matter.
Purpose of this lesson
Apply ORDER BY correctly in a TechLearningPRO production database — with clear query intent, safe defaults, and failure modes you can explain in review.
Understanding the topic
Core concepts to understand:
ORDER BY created_at DESC— newest first.ORDER BY country, name— group by country, then alphabetize.- Use
NULLS FIRST/LASTin Postgres to control NULL position. - Sorting big sets is expensive — back it with an index.
- Pair with LIMIT for top-N queries.
Step-by-step explanation
- State the business question ORDER BY answers and the tables involved.
- Read the workflow diagram and map each stage to parser, optimizer, or storage.
- Write the smallest correct statement (or design change) for a TechLearningPRO Orders/learners dataset.
- Predict the failure mode: wrong cardinality, missing index, or unsafe write — then verify.
Syntax reference
Visual workflow / architecture:
unsorted rows│▼in-memory or disk sort│▼sorted rows──── LIMIT 10 ────▶ top resultsIndexed sort: rows already in order → instant
SELECT <cols>
FROM <table>
ORDER BY <col1> [ASC|DESC] [, <col2> ...]
[NULLS FIRST|LAST];ORDER BYSort the result by one or more columns.ASC / DESCAscending (default) or descending.NULLS LASTPush NULL values to the end (Postgres).
SELECT name, scoreFROM playersORDER BY score DESC, name ASC;
| name | score |
|---|---|
| Ana | 84 |
| Leo | 91 |
| Mia | 91 |
| Rio | 72 |
| name | score |
|---|---|
| Leo | 91 |
| Mia | 91 |
| Ana | 84 |
| Rio | 72 |
An index on the ORDER BY column lets the DB skip the sort entirely.
Informative example
Worked SQL example:
SELECT name, scoreFROM playersORDER BY score DESC, name ASC;
Real-world use
Twitter timelines, news feeds, leaderboards and 'recent orders' tables are all ORDER BY + LIMIT. With proper indexes, even billion-row tables answer in milliseconds.
Security implications
SQL is a trust boundary. Application code must never concatenate untrusted input into statements.
- Use bind parameters / prepared statements — never string-built SQL from request bodies.
- Least-privilege DB roles: app users should not own DDL in production.
- Avoid returning raw DB errors to clients; log server-side with a correlation id.
Best practices
- Always have an index that matches the ORDER BY for big tables.
- Order by stable, indexed columns; avoid
ORDER BY random()in hot paths. - Use
LIMITwith ORDER BY — never sort entire tables for a UI.
Common mistakes
- Selecting
*in application queries and shipping wide rows over the network. - Filtering on expressions that defeat indexes (
WHERE YEAR(created_at) = 2026). - Running unbounded deletes/updates without a dry-run
SELECTfirst.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionQ1. Default direction of ORDER BY.+
Answer
2IntermediateQuestionQ2. How to put NULLs last in Postgres.+
Answer
3IntermediateQuestionQ3. Why is sorting expensive without indexes?+
Answer
4AdvancedQuestionQ4. ORDER BY 1, 2 — what does it mean?+
Answer
5AdvancedQuestionQ5. Top-N pattern.+
Answer
Hands-on exercise
Hands-on + interview drill:
- Implement the smallest correct example for ORDER BY on an Orders-like schema.
- Q1. Default direction of ORDER BY.
- Q2. How to put NULLs last in Postgres.
- Q3. Why is sorting expensive without indexes?
- Q4. ORDER BY 1, 2 — what does it mean?
- Q5. Top-N pattern.
Summary
ORDER BY is a production SQL skill: state the question, write the precise statement, and prove it with an execution plan or constraint — not with lucky result sets.