Sorting with ORDER BY
SQL · 16 questions
Short notes
Key idea
ORDER BY sorts the result. It runs near the end, after SELECT, so it can use column aliases. Combined with LIMIT it answers "top N" questions.
Syntax
SELECT name, city, total
FROM customers
ORDER BY city ASC, total DESC
LIMIT 3;
ASC(the default) is smallest first;DESCis largest first.- Each column has its own direction.
NULLS FIRST/NULLS LASTcontrol where missing values go.
Example
The five most expensive products:
SELECT product_name, price
FROM products
ORDER BY price DESC
LIMIT 5;
Traps
DESCapplies only to the column just before it.ORDER BY city, total DESCsorts city ascending.- Ties: if two rows share the 5th price,
LIMIT 5picks one of them arbitrarily. Add a second sort column to make it stable. - Text sorts as text: '100' comes before '20' if the column is a string.
- Databases disagree on NULLs: DuckDB puts them last both ways; PostgreSQL puts them first when sorting descending. Say
NULLS LASTwhen it matters.
Want the full lesson with step-by-step examples, a project and a certificate? SQL course, ₹120 →
- Question 1easy
What is the default sort direction of
ORDER BY price? - Question 2medium
In
ORDER BY category, price DESC, how iscategorysorted? - Question 3medium
A query has no
ORDER BY. Which statement is true? - Question 4medium
What does this return?
SELECT price FROM (SELECT price FROM products ORDER BY price DESC LIMIT 3) ORDER BY price LIMIT 1;
- Question 5medium
SELECT order_id FROM orders ORDER BY order_date DESC LIMIT 1;sometimes returns order 53 and sometimes order 54. Both were placed on the same day. What's the best fix?
Sorting with ORDER BY
Sorting with ORDER BY
Sorting with ORDER BY
Sorting with ORDER BY
Sorting with ORDER BY
11 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.