Course Resources

Search

Search IconIcon to open search

Last updated Nov 17, 2024

# Select and Filter Data - ORDER BY

The ORDER BY clause is used to sort the result set of a query by one or more columns. It can sort the data in ascending or descending order. By default, it sorts in ascending order.

ORDER BY must come after the WHERE clause. This makes sense if we think about it, we do not want to sort the rows until we’ve already filtered out the ones we don’t want.

Using the Employees table from the previous example:

EmployeeIDNameAgeDepartment
1John Doe28Marketing
2Jane Doe32HR
3Alex Ray45IT
4Sara Ali30Finance
5Mia Chen26Marketing

We can sort the results by columns such as age with:

1
2
SELECT * FROM Employees
ORDER BY Age;
# Expected Output
EmployeeIDNameAgeDepartment
5Mia Chen26Marketing
1John Doe28Marketing
4Sara Ali30Finance
2Jane Doe32HR
3Alex Ray45IT

If we instead wrote:

1
2
SELECT * FROM Employees
ORDER BY Age DESC;

We would get the same list but sorted from the highest to lowest age.

It is also possible to ORDER BY multiple columns:

1
2
SELECT * FROM Employees
ORDER BY Department, Age;
# Expected Output:
EmployeeIDNameAgeDepartment
4Sara Ali30Finance
2Jane Doe32HR
3Alex Ray45IT
5Mia Chen26Marketing
1John Doe28Marketing

In this ordered list, employees are sorted by their departments (‘Finance’, ‘HR’, ‘IT’, and ‘Marketing’), and within each department, they are sorted by their age from youngest to oldest.

# Practice Questions

  1. Write a query to select all customers and order them alphabetically by the customer name.

  2. Write a query to select all customers and order them by their Ids from highest to lowest.

# Lessons