Lesson 4: Sorting Data with ORDER BY
What is ORDER BY?
The ORDER BY
clause sorts query results based on one or more columns. By default, it sorts in ascending order.
SQL
SELECT first_name, last_name, city
FROM customers
ORDER BY last_name;
ASC vs DESC
You can specify the sort order using ASC
(ascending, default) or DESC
(descending).
SQL
SELECT first_name, age
FROM customers
ORDER BY age DESC;
Sorting by Multiple Columns
You can sort by more than one column by listing them, separated by commas. SQL applies sorting in the order listed.
SQL
SELECT first_name, last_name, city
FROM customers
ORDER BY city ASC, last_name ASC;
ORDER BY with Aliases
You can also use column aliases defined in the SELECT
clause inside ORDER BY
.
SQL
SELECT first_name AS fname, last_name AS lname
FROM customers
ORDER BY lname;
Practice Quiz
Test your understanding of ORDER BY: