ORDER BY
In one line
ORDER BY sorts the query results by specified columns, either ascending (ASC) or descending (DESC).
In simple words
ORDER BY sorts the rows in the result set. You specify one or more columns and a direction — ASC (ascending, the default) or DESC (descending).
You can sort by multiple columns: the first column is the primary sort key, and subsequent columns break ties. For example, ORDER BY last_name ASC, first_name ASC sorts by last name, then by first name for people with the same last name.
ORDER BY is applied after WHERE, GROUP BY, and HAVING — it sorts the final result set. It can be slow on large result sets without an index on the sort column.
Example
-- Sort users by creation date, newest first
SELECT * FROM users
ORDER BY created_at DESC;
-- Sort by last name, then first name
SELECT * FROM users
ORDER BY last_name ASC, first_name ASC;The first query sorts newest-first. The second sorts by last name, breaking ties with first name.
Related terms
Related Resources
Related Lessons
- Select Queries
Learn sorting and other SELECT features.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.