Aral Code

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

SQL Products from cheapest to most expensive
SELECT name, price
FROM products
ORDER BY price;

The default is ascending (ASC): smallest to largest, A to Z, oldest to newest.

Sorting descending

SQL Most expensive first
SELECT name, price
FROM products
ORDER BY price DESC;

Sorting text

SQL Customers in alphabetical order
SELECT name, barangay
FROM customers
ORDER BY name;

Sorting by several columns

When rows tie on the first column, the second column decides:

SQL By category, then by price within each category
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.

SQL Class list: by grade level (highest first), then last name
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.

SQL Top Math scores
SELECT student_id, score
FROM grades
WHERE subject = 'Math'
ORDER BY score DESC;

Sorting by a computed value

SQL Products by total stock 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

SQL Newest orders first
SELECT id, order_date, status
FROM orders
ORDER BY order_date DESC;

Where do NULLs go?

SQL Customers sorted by phone (NULLs appear first)
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. 🙂

1. How do you sort prices from highest to lowest?
2. What is the default sort direction?
3. In ORDER BY grade DESC, last_name, how is last_name sorted?
4. Which order of clauses is correct?

By Sir Reyel · Last updated 2026-12-04