Databases & SQL Master Course — 007. Sorting and Limiting Results
Lesson 007 Sorting and Limiting Results
A colleague asks for the two cheapest books. Filtering alone cannot answer which two should appear first. You need a ranking rule, a tie policy, and a limit. In this lesson you will make those choices explicit and learn why a result that looks sorted by accident is not a reliable report.
Prerequisites and objectives
Complete Lesson 006. You should be able to select columns and filter rows with one condition. You will sort ascending and descending, use several ordering keys, limit a result, read a simple offset, and explain the difference between a deterministic selection and all tied results. No Python is required.
Step 1 Prepare a reproducible fixture
Run this setup once in a fresh SQLite scratch database, with foreign keys enabled outside a transaction. The two books priced at 1800 are essential: they expose what happens when the main sort key is tied.
PRAGMA foreign_keys = ON;
CREATE TABLE authors (
author_id INTEGER PRIMARY KEY,
author_name TEXT NOT NULL
);
CREATE TABLE books (
book_id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
author_id INTEGER NOT NULL REFERENCES authors(author_id),
genre TEXT NOT NULL,
price_cents INTEGER NOT NULL,
stock INTEGER NOT NULL
);
INSERT INTO authors (author_id, author_name) VALUES
(1, 'Mira Chen'), (2, 'Omar Silva'), (3, 'Nia Patel');
INSERT INTO books
(book_id, title, author_id, genre, price_cents, stock) VALUES
(101, 'River Maps', 1, 'Travel', 1800, 4),
(102, 'SQL Trail', 2, 'Technology', 2500, 8),
(103, 'Garden Notes', 3, 'Nature', 1200, 0),
(104, 'Night Signals', 1, 'Fiction', 1800, 5);
Our table has a primary key, but that does not make every query automatically return primary-key order. A storage layout or query plan may happen to produce a familiar sequence today. The statement must request an order if the report depends on one.
Step 2 Order by a meaningful field
For a cheapest-first price list, order by price_cents ascending. ASC means ascending and is the default direction. We add book_id as a second key to make equal prices reproducible.
SELECT book_id, title, price_cents FROM books
ORDER BY price_cents ASC, book_id ASC;
The expected IDs are 103, 101, 104, and 102. First compare prices. Only when two prices tie does book_id decide between those rows. The second key does not reorder books across different price groups. A unique final key gives a dependable order for this fixed dataset.
Step 3 Set each direction separately
DESC requests descending values. Suppose the most-stocked books should appear first, with ascending identifiers breaking any quantity ties. Each ordering term has its own direction.
SELECT book_id, title, stock FROM books
ORDER BY stock DESC, book_id ASC;
The IDs are 102, 104, 101, and 103. Writing DESC on the first term does not turn every later term into descending order. Say the rule aloud: descending stock, then ascending book ID. That is clearer than describing the result vaguely as “sorted.”
Step 4 Limit an already defined order
LIMIT 2 requests at most two result rows. Combine it with the complete price ordering to answer the original question.
SELECT book_id, title, price_cents FROM books
ORDER BY price_cents, book_id
LIMIT 2;
Garden Notes and River Maps are returned. Night Signals has the same price as River Maps but is excluded because our rule asks for two rows and resolves the tie by book ID. This is a policy choice. If the business request means every book tied within the cheapest price levels, a simple row limit is insufficient; later ranking lessons cover that different question.
A limit without ordering can return any qualifying subset consistent with the execution. Repeating the query and getting the same two rows is not a guarantee. A predictable top-two report needs both the ordering meaning and the tie-breaker, not merely a small number at the end.
Step 5 Filter before selecting the leading rows
The shop now asks for the two cheapest available titles. Apply stock > 0 to define the candidate population, then order and limit that population. Garden Notes should no longer compete because its recorded stock is zero.
SELECT book_id, title, price_cents FROM books
WHERE stock > 0
ORDER BY price_cents, book_id
LIMIT 2;
The expected answer is River Maps and Night Signals. Taking two rows first and then discarding out-of-stock ones would answer a different question and could leave too few results. Think through the population before the ranking. SQL’s written clause order also matters: WHERE precedes ORDER BY, and LIMIT follows it here.

Step 6 Understand a simple offset
OFFSET skips a number of ordered result rows before returning the limited portion. This example asks for the next two rows after the cheapest two.
SELECT book_id, title FROM books
ORDER BY price_cents, book_id
LIMIT 2 OFFSET 2;
The result is Night Signals and SQL Trail. OFFSET 2 skips two rows, not two distinct prices. This is useful for understanding small result pages, but offsets alone do not create a stable snapshot. New data or changed prices between requests can shift positions, causing repeats or omissions. Later application lessons introduce stronger pagination designs.
Step 7 Verify the contract
A sorted report has several independent checks: every returned row meets its filter, adjacent rows obey the sort rule, tied rows follow the stated policy, and the count stays within the limit. Do not test only the count. A wrong ordering can still return exactly two rows, and a wrong filter can still produce a convincing-looking price list.
These examples use SQLite syntax. LIMIT and its offset spelling are dialect details to verify when moving between systems; do not infer complete portability from a shared keyword. Text sorting also depends on collation, while missing-value ordering has engine-specific defaults. The present numeric, non-NULL sort keys keep those topics separate.
Practice with worked solutions
Exercise 1
Return the highest-priced book. Use book_id ascending to settle any price tie.
Worked solution
SELECT book_id, title, price_cents FROM books
ORDER BY price_cents DESC, book_id ASC
LIMIT 1;
SQL Trail is first at 2500. The tie policy remains worth stating even though this fixture has a unique highest price; it protects the intended behavior when data changes.
Exercise 2
List all books by ascending stock, then ascending identifier.
Worked solution
SELECT book_id, stock FROM books
ORDER BY stock ASC, book_id ASC;
The ID order is 103, 101, 104, 102. Zero stock appears first because the quantities are ascending, not because zero means a missing observation.
Exercise 3
Return exactly the third row of the cheapest-first list, if present.
Worked solution
SELECT book_id, title FROM books
ORDER BY price_cents, book_id
LIMIT 1 OFFSET 2;
Skip the first two ordered rows and take one. Night Signals is third under the complete price-and-ID ordering. Offset counts skipped rows, so the third position uses two.
Exercise 4
Request ten rows from the four-row table and explain the result size.
Worked solution
SELECT book_id FROM books ORDER BY book_id LIMIT 10;
Four rows are returned. LIMIT sets a maximum rather than manufacturing enough rows to reach the requested number. All four source rows remain unchanged.
Knowledge check
Question 1
Which clause requests a guaranteed result order?
- WHERE
- ORDER BY
- FROM
- AS
Answer and explanation
B. ORDER BY defines the requested sequence. The other clauses have different roles.
Question 2
What does the second ordering key decide?
- Every row before the first key
- Only the row count
- Order among rows tied on earlier keys
- Which table exists
Answer and explanation
C. Later keys break ties left unresolved by earlier keys.
Question 3
What does LIMIT 2 guarantee here?
- At most two result rows
- All tied prices
- Exactly two rows even in an empty table
- Permanent sorting of storage
Answer and explanation
A. It bounds the output size; ties and missing rows require separate reasoning.
Question 4
What does OFFSET 2 skip?
- Two columns
- Two tables
- Two price groups
- Two ordered rows
Answer and explanation
D. It skips row positions, regardless of whether the price values repeat.
Question 5
Why add a unique tie-breaker?
- To modify prices
- To resolve otherwise tied row order
- To prevent all future data changes
- To replace filtering
Answer and explanation
B. A unique final key makes the chosen ordering unambiguous for the current data.
Pitfalls and summary
Do not rely on insertion order, apply one direction to every key by assumption, or confuse the first two rows with all tied winners. Define the eligible population, specify a complete order, and then limit it. Predictable reports make their ranking and tie policies visible.
Primary references
Official documentation checked on 10 October 2026.
- SQLite SELECT ordering and limits: ORDER BY terms, LIMIT, and OFFSET semantics.
- SQLite query planner: Why physical access choices are separate from a requested order.
- SQLite expressions: Comparison expressions used for the candidate population.