ποΈ SQL Β· Topic 4 of 20
Sorting & Limiting β SQL Questions with Answers
30 practice questions on Sorting & Limiting, each with the correct answer and a clear explanation of why it is right. Read through them as revision notes, or take this topic as an interactive quiz to test yourself.
2 easy Β· 18 medium Β· 10 hard Β· Part of SQL: Databases from basics to window functions - 20 topics.
Medium questions (18)
Q3. medium
How do you sort by class ascending, then by marks descending within each class?
- A ORDER BY class ASC, marks DESC
- B ORDER BY class, marks ASC DESC
- C ORDER BY class AND marks DESC
- D ORDER BY class DESC marks
Answer: A β ORDER BY class ASC, marks DESC
List columns in priority order, each with its own direction. The second column only breaks ties within equal values of the first.
Multi-column sort
Q5. medium
Can you sort by a column that is NOT in the SELECT list?
- A Yes - ORDER BY can use any column from the source table
- B No, it must be selected
- C Only with an alias
- D Only for numbers
Answer: A β Yes - ORDER BY can use any column from the source table
SELECT name FROM students ORDER BY marks works fine. (The exception is with SELECT DISTINCT or UNION, where the sort column must appear in the result.)
ORDER BYDISTINCT
Q6. medium
Can ORDER BY use a column ALIAS defined in SELECT?
SELECT price * qty AS total
FROM items
ORDER BY total DESC; -- alias works here
- A Yes - ORDER BY runs AFTER SELECT, so the alias exists
- B No, aliases never work there
- C Only in MySQL
- D Only for computed columns
Answer: A β Yes - ORDER BY runs AFTER SELECT, so the alias exists
This is the mirror of the WHERE rule: WHERE runs before SELECT (no alias), ORDER BY runs after (alias available).
AliasesExecution order
Q8. medium
Which clause limits how many rows are returned in MySQL/PostgreSQL?
-- MySQL / PostgreSQL
SELECT * FROM students ORDER BY marks DESC LIMIT 10;
-- SQL Server
SELECT TOP 10 * FROM students ORDER BY marks DESC;
- A LIMIT 10
- B TOP 10
- C MAX 10
- D FIRST 10
Answer: A β LIMIT 10
MySQL, PostgreSQL and SQLite use LIMIT. SQL Server uses SELECT TOP 10, and the SQL standard is FETCH FIRST 10 ROWS ONLY.
LIMITTOPDialects
Q10. medium
What does OFFSET do?
LIMIT 10 OFFSET 20
SELECT * FROM posts
ORDER BY created_at DESC
LIMIT 10 OFFSET 20; -- page 3
- A Skips the first 20 rows, then returns the next 10 - used for pagination
- B Returns rows 10 to 20
- C Skips 10 rows
- D Returns 30 rows
Answer: A β Skips the first 20 rows, then returns the next 10 - used for pagination
For page N with a page size of 10: OFFSET = (N - 1) * 10. Page 3 skips 20 rows.
OFFSETPagination
Q12. medium
Where do NULLs appear when sorting ascending?
ORDER BY score DESC NULLS LAST; -- PostgreSQL/Oracle
- A It depends on the database - PostgreSQL puts them LAST, MySQL puts them FIRST
- B Always first
- C Always last
- D They are excluded
Answer: A β It depends on the database - PostgreSQL puts them LAST, MySQL puts them FIRST
For portable, explicit control use NULLS FIRST / NULLS LAST where supported, or sort on a CASE expression that maps NULLs to a chosen position.
NULLSorting
Q14. medium
How do numbers stored as TEXT sort?
- A Alphabetically - so '10' comes before '9'
- B Numerically
- C Randomly
- D They cannot be sorted
Answer: A β Alphabetically - so '10' comes before '9'
Character-by-character comparison puts '10' before '9' because '1' < '9'. Cast to a number to fix it: ORDER BY CAST(code AS INT). Better still, store numbers in numeric columns.
Data typesCAST
Q15. medium
How do you find the single highest-scoring student?
- A SELECT * FROM students ORDER BY marks DESC LIMIT 1;
- B SELECT MAX(*) FROM students;
- C SELECT TOP marks FROM students;
- D SELECT FIRST(marks) FROM students;
Answer: A β SELECT * FROM students ORDER BY marks DESC LIMIT 1;
Sorting descending and taking one row also gives you the whole row, not just the maximum value (which is all MAX(marks) would return).
LIMITMAX
Q17. medium
How do you get a random row?
- A ORDER BY RANDOM() LIMIT 1 (RAND() in MySQL, NEWID() in SQL Server)
- B SELECT RANDOM FROM t
- C LIMIT RANDOM
- D It is not possible
Answer: A β ORDER BY RANDOM() LIMIT 1 (RAND() in MySQL, NEWID() in SQL Server)
It works but is expensive on big tables because every row gets a random value and the whole set is sorted. For large data, sample by id range instead.
RandomPerformance
Q18. medium
Does ORDER BY affect which rows are returned?
- A No - it only changes their ORDER (unless combined with LIMIT)
- B Yes, it filters rows
- C Yes, it removes duplicates
- D It groups rows
Answer: A β No - it only changes their ORDER (unless combined with LIMIT)
Filtering is WHERE's job. But with LIMIT, the order determines WHICH rows survive the cut - which is why the pair must be considered together.
ORDER BYLIMIT
Q20. medium
How do you sort case-insensitively?
- A ORDER BY LOWER(name)
- B ORDER BY name IGNORE CASE
- C ORDER BY name ASC ASC
- D It is automatic everywhere
Answer: A β ORDER BY LOWER(name)
Without it, some databases place all capitals before lowercase, so 'Zoe' sorts before 'anna'. Collation settings can also control this.
CollationLOWER
Q21. medium
How do you show the 5 most recent orders?
- A ORDER BY order_date DESC LIMIT 5
- B ORDER BY order_date ASC LIMIT 5
- C LIMIT 5 ORDER BY order_date
- D SELECT LAST 5 FROM orders
Answer: A β ORDER BY order_date DESC LIMIT 5
Most recent means largest date, so sort descending. Option B would give the five OLDEST orders.
DatesLIMIT
Q23. medium
Which is the SQL-standard way to limit rows?
SELECT * FROM t ORDER BY id
OFFSET 20 ROWS FETCH FIRST 10 ROWS ONLY;
- A FETCH FIRST 10 ROWS ONLY
- B LIMIT 10
- C TOP 10
- D ROWNUM <= 10
Answer: A β FETCH FIRST 10 ROWS ONLY
OFFSET ... FETCH is the standard, supported by PostgreSQL, Oracle 12c+ and SQL Server. LIMIT is more common in practice; ROWNUM is old Oracle syntax.
StandardsDialects
Q24. medium
Can you use ORDER BY inside a subquery meaningfully?
- A Usually not - the outer query may reorder it; it only matters with LIMIT inside the subquery
- B Yes, order is always preserved
- C It is a syntax error
- D Only in views
Answer: A β Usually not - the outer query may reorder it; it only matters with LIMIT inside the subquery
Sorting a subquery is generally pointless (and some databases forbid it without LIMIT). Apply ORDER BY at the outermost level.
SubqueriesORDER BY
Q26. medium
Does ORDER BY slow down a query?
- A It can, since sorting takes work - but an index on the sort column can make it nearly free
- B Never
- C Always doubles the time
- D Only with LIMIT
Answer: A β It can, since sorting takes work - but an index on the sort column can make it nearly free
If an index already stores rows in the required order, the database can read them in order and skip sorting entirely - a big win for paginated queries.
IndexesPerformance
Q27. medium
How do you return rows 11-20 of a sorted list?
- A ORDER BY ... LIMIT 10 OFFSET 10
- B LIMIT 11, 20
- C BETWEEN 11 AND 20
- D OFFSET 20 LIMIT 10
Answer: A β ORDER BY ... LIMIT 10 OFFSET 10
Skip the first 10, then take 10. (MySQL also supports the shorthand LIMIT 10, 10 where the first number is the offset - easy to misread.)
PaginationOFFSET
Q29. medium
What is the safest ORDER BY for a paginated API?
- A A meaningful column plus a unique tiebreaker: ORDER BY created_at DESC, id DESC
- B ORDER BY created_at only
- C No ORDER BY, just LIMIT
- D ORDER BY RANDOM()
Answer: A β A meaningful column plus a unique tiebreaker: ORDER BY created_at DESC, id DESC
The unique column guarantees a total order, so pages never overlap or skip rows when timestamps are identical.
PaginationStability
Q30. medium
What does this query answer?
SELECT city, COUNT(*) AS n FROM customers GROUP BY city ORDER BY n DESC LIMIT 3;
- A The three cities with the most customers
- B The first three cities alphabetically
- C Three random customers
- D It is invalid
Answer: A β The three cities with the most customers
Group to count per city, sort by that count descending, then keep the top 3 - the standard 'top N by category' report pattern.
GROUP BYTop N
Hard questions (10)
Q4. hard
Is the row order guaranteed WITHOUT an ORDER BY?
- A No - never rely on it, even if results look sorted; the database may return rows in any order
- B Yes, always insertion order
- C Yes, primary key order
- D Yes, alphabetical
Answer: A β No - never rely on it, even if results look sorted; the database may return rows in any order
Order can change with indexes, parallel execution or data growth. If order matters, say so explicitly with ORDER BY.
- A classic source of bugs that appear only in production.
ORDER BYGuarantees
Q7. hard
What does ORDER BY 2 mean?
- A Sort by the SECOND column in the SELECT list (positional reference)
- B Sort by the value 2
- C Return 2 rows
- D A syntax error
Answer: A β Sort by the SECOND column in the SELECT list (positional reference)
It works, but it is fragile: changing the SELECT list silently changes the sort. Name the column or alias instead.
Positional sortBest practices
Q9. hard
Why must LIMIT almost always be paired with ORDER BY?
- A Without a defined order, 'the top 10' is arbitrary and can differ between runs
- B LIMIT is a syntax error alone
- C It is only for performance
- D They are unrelated
Answer: A β Without a defined order, 'the top 10' is arbitrary and can differ between runs
LIMIT truncates whatever order the database happened to produce. 'Top 10 scorers' only means something after ORDER BY marks DESC.
LIMITORDER BY
Q11. hard
Why does OFFSET become slow on very large tables?
- A The database must still read and discard all skipped rows - OFFSET 100000 scans 100,000 rows first
- B It locks the table
- C It uses no index at all
- D It is not slow
Answer: A β The database must still read and discard all skipped rows - OFFSET 100000 scans 100,000 rows first
For deep pagination, use keyset (cursor) pagination instead: remember the last row's sort value and filter WHERE id > last_id ORDER BY id LIMIT 10.
PaginationPerformanceKeyset pagination
Q13. hard
How would you sort so that a specific status appears first?
- A ORDER BY CASE WHEN status = 'urgent' THEN 0 ELSE 1 END, created_at
- B ORDER BY status = 'urgent'
- C ORDER BY urgent FIRST
- D It is impossible
Answer: A β ORDER BY CASE WHEN status = 'urgent' THEN 0 ELSE 1 END, created_at
A CASE expression creates a custom sort key. This 'priority sort' pattern is very common for dashboards and task lists.
CASECustom sorting
Q16. hard
What is a problem with ORDER BY marks DESC LIMIT 1 when there are TIES?
- A It arbitrarily picks ONE of the tied rows - the others are hidden
- B It errors on ties
- C It returns all tied rows
- D Ties are impossible
Answer: A β It arbitrarily picks ONE of the tied rows - the others are hidden
To return every top scorer, use a subquery (WHERE marks = (SELECT MAX(marks) ...)) or window functions with RANK(), which is covered in topic 20.
TiesRANK
Q19. hard
In which order does the database EXECUTE these clauses?
SELECT / FROM / WHERE / ORDER BY / LIMIT
- A FROM, WHERE, SELECT, ORDER BY, LIMIT
- B SELECT, FROM, WHERE, ORDER BY, LIMIT
- C LIMIT, ORDER BY, WHERE, FROM, SELECT
- D The same order as written
Answer: A β FROM, WHERE, SELECT, ORDER BY, LIMIT
Data is read, filtered, projected, sorted and finally truncated. This explains why aliases work in ORDER BY but not WHERE, and why LIMIT applies to sorted output.
Execution order
Q22. hard
Why might the same LIMIT query return different rows on different runs?
- A Because ties (or a missing ORDER BY) leave the order undefined - add a unique tiebreaker column
- B Because LIMIT is random
- C Because of caching
- D It cannot happen
Answer: A β Because ties (or a missing ORDER BY) leave the order undefined - add a unique tiebreaker column
For stable pagination always end with a unique column: ORDER BY created_at DESC, id DESC. Otherwise rows can repeat or vanish between pages.
PaginationDeterministic order
Q25. hard
How do you sort by a value's position in a custom list?
ORDER BY CASE size
WHEN 'S' THEN 1 WHEN 'M' THEN 2
WHEN 'L' THEN 3 ELSE 4 END;
- A Use CASE (or FIELD() in MySQL) to map each value to a sort number
- B ORDER BY LIST(...)
- C ORDER BY IN (...)
- D It is impossible
Answer: A β Use CASE (or FIELD() in MySQL) to map each value to a sort number
For example ordering sizes S, M, L, XL - which are neither alphabetical nor numeric. Map them explicitly.
CASECustom order
Q28. hard
What does DISTINCT combined with ORDER BY require?
- A The ORDER BY columns must appear in the SELECT list
- B Nothing special
- C DISTINCT cannot be sorted
- D ORDER BY must come first
Answer: A β The ORDER BY columns must appear in the SELECT list
After DISTINCT collapses rows, a column that was not selected no longer has a single well-defined value to sort by, so most databases reject it.
DISTINCTORDER BY