# 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:
EmployeeID | Name | Age | Department |
---|---|---|---|
1 | John Doe | 28 | Marketing |
2 | Jane Doe | 32 | HR |
3 | Alex Ray | 45 | IT |
4 | Sara Ali | 30 | Finance |
5 | Mia Chen | 26 | Marketing |
We can sort the results by columns such as age with:
|
|
# Expected Output
EmployeeID | Name | Age | Department |
---|---|---|---|
5 | Mia Chen | 26 | Marketing |
1 | John Doe | 28 | Marketing |
4 | Sara Ali | 30 | Finance |
2 | Jane Doe | 32 | HR |
3 | Alex Ray | 45 | IT |
If we instead wrote:
|
|
We would get the same list but sorted from the highest to lowest age.
It is also possible to ORDER BY
multiple columns:
|
|
# Expected Output:
EmployeeID | Name | Age | Department |
---|---|---|---|
4 | Sara Ali | 30 | Finance |
2 | Jane Doe | 32 | HR |
3 | Alex Ray | 45 | IT |
5 | Mia Chen | 26 | Marketing |
1 | John Doe | 28 | Marketing |
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
Write a query to select all customers and order them alphabetically by the customer name.
Write a query to select all customers and order them by their Ids from highest to lowest.
# Lessons
- SQL - W2 Select and Filter Data - Introduction
- SQL - W2 Select and Filter Data - Creating a Database
- SQL - W2 Select and Filter Data - Running Scripts
- SQL - W2 Select and Filter Data - SELECT Statement
- SQL - W2 Select and Filter Data - WHERE Clause and Comparison Operators
- SQL - W2 Select and Filter Data - Logical Operators
- SQL - W2 Select and Filter Data - ORDER BY
- Next: SQL - W2 Select and Filter Data - SQL Comments
- SQL - W2 Select and Filter Data - Note on Semicolons
- SQL - W2 Select and Filter Data - Practice Assignment