Sorting with ORDER BY
Order rows ascending and descending.
Why Order Matters
By default, a SELECT returns rows in no guaranteed order. The database is free to hand them back in whatever sequence is convenient.
When you need predictable output, like an alphabetical list or newest-first feed, you must ask for it explicitly with ORDER BY.
-- Without ORDER BY, row order is NOT guaranteed
SELECT name, price
FROM products;The ORDER BY Clause
ORDER BY goes near the end of a query, after WHERE and before LIMIT. You name the column to sort on.
This sorts products alphabetically by name.
SELECT name, price
FROM products
ORDER BY name;All lessons in this course
- Sorting with ORDER BY
- Sorting by Multiple Columns
- LIMIT and OFFSET
- Finding Top-N Records