You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
By default, databases return rows in an unspecified order. Use ORDER BY to control the sort order of your results.
SELECT columns
FROM table
WHERE condition
ORDER BY column [ASC | DESC];
ASC — ascending order (A→Z, 1→9) — this is the defaultDESC — descending order (Z→A, 9→1)-- Cheapest products first
SELECT name, price
FROM products
ORDER BY price ASC;
-- Most expensive first
SELECT name, price
FROM products
ORDER BY price DESC;
Result (DESC):
name | price
--------------------+---------
Laptop Pro 15" | 1299.99
Standing Desk | 449.99
Office Chair | 299.99
Mechanical Keyboard | 89.99
USB-C Hub | 39.99
Desk Lamp | 29.99
Notebook (paper) | 4.99
-- Alphabetical by product name
SELECT name, category
FROM products
ORDER BY name ASC;
Text sorting is alphabetical (A-Z for ASC). Note that in most databases, uppercase letters sort before lowercase by default.
You can sort by multiple columns — the database sorts by the first column first, then uses subsequent columns to break ties:
-- Sort by category, then by price within each category
SELECT name, category, price
FROM products
ORDER BY category ASC, price DESC;
Result:
name | category | price
--------------------+-------------+--------
Laptop Pro 15" | Electronics | 1299.99
Mechanical Keyboard | Electronics | 89.99
USB-C Hub | Electronics | 39.99
Standing Desk | Furniture | 449.99
Office Chair | Furniture | 299.99
Desk Lamp | Office | 29.99
Notebook (paper) | Office | 4.99
You can reference columns by their position in the SELECT list:
-- Same as ORDER BY price DESC
SELECT name, price
FROM products
ORDER BY 2 DESC;
This is useful for dynamic queries but can make code harder to read — use sparingly.
ORDER BY comes after WHERE:
SELECT name, price
FROM products
WHERE category = 'Electronics'
ORDER BY price DESC;
Combine with LIMIT to get "top N" results:
-- Top 3 most expensive products
SELECT name, price
FROM products
ORDER BY price DESC
LIMIT 3;
Result:
name | price
----------------+---------
Laptop Pro 15" | 1299.99
Standing Desk | 449.99
Office Chair | 299.99
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.