Filtering & Sorting Lesson 6 of 21
SQL ORDER BY — Sorting Results
Sort query results with ORDER BY in ascending (ASC) or descending (DESC) order, by several columns, and by computed values.
Rows in a database have no guaranteed order. If you want the cheapest products first, or students sorted alphabetically, you must ask for it with ORDER BY.
Sorting ascending
SELECT name, price
FROM products
ORDER BY price;
The default is ascending (ASC): smallest to largest, A to Z, oldest to newest.
Sorting descending
SELECT name, price
FROM products
ORDER BY price DESC;
Sorting text
SELECT name, barangay
FROM customers
ORDER BY name;
Sorting by several columns
When rows tie on the first column, the second column decides:
SELECT category, name, price
FROM products
ORDER BY category, price DESC;
Categories are A–Z, and inside each category the prices go from highest to lowest. Each column can have its own ASC or DESC.
SELECT grade, last_name, first_name, section
FROM students
ORDER BY grade DESC, last_name;
ORDER BY with WHERE
The order of the parts matters: SELECT → FROM → WHERE → ORDER BY.
SELECT student_id, score
FROM grades
WHERE subject = 'Math'
ORDER BY score DESC;
Sorting by a computed value
SELECT name, price * stock AS stock_value
FROM products
ORDER BY stock_value DESC;
You can sort by an alias created in the SELECT.
Sorting dates
SELECT id, order_date, status
FROM orders
ORDER BY order_date DESC;
Where do NULLs go?
SELECT name, phone
FROM customers
ORDER BY phone;
In SQLite and MySQL, NULL values come first in ascending order and last in descending order.
Quick Quiz
Check what you learned. Walang grade ito, practice lang. 🙂
By Sir Reyel · Last updated 2026-12-04