SQLite ORDER BY: Ascending, Descending and Stable Results
ORDER BY determines the order of a query result. Without it, SQLite does not promise a particular row order. Sort the query itself when you need ordering across the whole dataset; sorting a preview only rearranges loaded rows.
Sort from low to high
ASC is the default. In the sample, Notebook set at 24 is first. A second ordering column makes equal prices predictable.
SELECT id, name, price FROM products
ORDER BY price ASC, id ASC;Open this example for review →Find the most expensive products
DESC reverses the order. Apply LIMIT after sorting. The sample returns Mechanical keyboard (129), Monitor stand (89), and Desk lamp (79).
SELECT name, price FROM products
ORDER BY price DESC, id ASC
LIMIT 3;Open this example for review →Sort aggregate results
You can order by an output alias. Grouping does not itself promise a final order. Add the customer name as a tie breaker when totals are equal.
SELECT c.name, SUM(o.total) AS spent
FROM customers c JOIN orders o ON o.customer_id = c.id
GROUP BY c.id
ORDER BY spent DESC, c.name;Open this example for review →Be intentional about NULL and text
NULL normally sorts before non-NULL values in ascending order. NULLS LAST makes the choice explicit. Numeric-looking TEXT follows text ordering, so 100 can sort before 20. Import numbers with an intentional type rather than assuming their appearance determines ordering.
SELECT name, email FROM customers
ORDER BY email ASC NULLS LAST, id;Open this example for review →Keep exploring
SQLite syntax reference · Practice with a learning path · Sample datasets
SQLite JOINs: Query Related Tables
Reference: Official SQLite documentation