ORDER BY

The ORDER BY clause sorts the rows returned by a query, based on one or more columns - either in ascending (default) or descending order.

Basic Syntax

SELECT * FROM customers
ORDER BY first_name;

Ascending vs Descending

-- Ascending (default)
SELECT * FROM orders ORDER BY amount ASC;

-- Descending
SELECT * FROM orders ORDER BY amount DESC;

Sorting by Multiple Columns

SELECT * FROM customers
ORDER BY city ASC, signup_date DESC;

Here, rows are sorted by city first, and for customers within the same city, by signup_date in descending order.

Combining with WHERE and LIMIT

-- Top 5 highest orders
SELECT * FROM orders
ORDER BY amount DESC
LIMIT 5;
ORDER BY is applied after WHERE filters the rows, so it only sorts the rows that already matched your conditions - not the entire table.

Ready to Master Data Science?

Join Uncodemy's Data Science Course and build real, job-ready skills with expert mentors.

Explore Course