CPCODELAB
SQL

ORDER BY — Sorting Results

6 min read

Sorting with ORDER BY

Without ORDER BY, the database can return rows in any order. Use ORDER BY to guarantee a predictable sort. You can sort by one or more columns, ascending (ASC, the default) or descending (DESC).

sql
-- Youngest students first
SELECT name, age FROM students ORDER BY age ASC;

-- Most expensive courses first
SELECT title, price FROM courses ORDER BY price DESC;

-- Sort by city, then by name within each city
SELECT name, city FROM students ORDER BY city ASC, name ASC;

NULL values sort last with ASC and first with DESC in most databases. Behaviour can differ between engines, so check your specific database's documentation when sorting nullable columns.

Ready to test yourself?
Practice SQL— quiz & coding exercises