Lesson 4: Sorting Data with ORDER BY

20 min read Beginner Lesson 4 of 12 12.8k learners

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:

1. Which clause is used to sort query results?
2. What is the default sort order in SQL?
3. How do you sort results in descending order?
4. Can you sort by multiple columns?
5. Which keyword sorts results from highest to lowest?