
📎 This article includes 2 downloadable practice files ↓
In this article
Without ORDER BY, a database returns rows in whatever order is convenient for it, which can change from one run to the next. If order matters, say so.
Sort ascending and descending
SELECT name, price FROM products ORDER BY price; -- cheapest first (ASC is the default)
SELECT name, price FROM products ORDER BY price DESC; -- most expensive first
Several columns
SELECT region, name FROM customers ORDER BY region, name;
SELECT category, name, price FROM products ORDER BY category, price DESC;
Sorted by the first column; ties broken by the second. Each column has its own ASC/DESC.
Top-N with LIMIT
SELECT name, price FROM products ORDER BY price LIMIT 3; -- 3 cheapest
SELECT order_id, order_date FROM orders ORDER BY order_date DESC LIMIT 5; -- 5 latest
LIMIT without ORDER BY gives “any 5 rows”, not the first or latest. Pair them.
Sort by a calculation or alias
SELECT name, price * (1 + gst_rate) AS with_gst
FROM products
ORDER BY with_gst DESC;
Paging: OFFSET
SELECT order_id FROM orders ORDER BY order_id LIMIT 10 OFFSET 20; -- rows 21-30
NULLs in sorting
SQLite and SQL Server put NULLs first in ascending order; PostgreSQL and Oracle put them last. Add NULLS LAST (PostgreSQL, Oracle, recent SQLite) when it matters.
Order of clauses
SELECT ... FROM ... WHERE ... ORDER BY ... LIMIT ...;
Always in this order. Lessons 5 adds GROUP BY and HAVING between WHERE and ORDER BY.
Where beginners go wrong
| Mistake | Result |
|---|---|
| Relying on default order | Reports change order between runs |
| LIMIT before ORDER BY | Syntax error |
| Numbers stored as text | Sorted ’10’ before ‘9’; store numbers as numbers |
Practice
Download shop.db and this lesson’s exercise file below. Open the database in the free DB Browser for SQLite (or sqlite3 shop.db), paste the exercises into the Execute SQL tab and write a query for each task. The expected result is printed under every task; answers are at the bottom of the file.
📎 Practice files for this article
- 📄Practice database (SQLite)shop.db: 12 customers, 10 products and 300 orders (April-September 2026).⬇ DB · 28 KB
- 🗃️Lesson 3 exercisesTasks with the expected result under each, and answers at the bottom.⬇ SQL · 2 KB
Free to use for learning. Files with macros (.bas) are plain text — import them with Alt+F11 → File → Import File, and always test on a copy.
Stuck on a step? Ask a question and the AI answers using this article.