SQL Cookbook Lesson
How to sort in SQL
Learn how to sort in SQL with examples and explanations from SQLPad.
Problem
You have a table of data in SQL and you need to sort the output of a query based on one or more columns.
Sample Data
Let's consider a sample data table named Employees:
| ID | Name | Department | HireDate |
|---|---|---|---|
| 1 | John | Marketing | 2015-06-28 |
| 2 | Sara | Sales | 2018-04-20 |
| 3 | Bill | HR | 2010-12-01 |
| 4 | Mary | IT | 2012-02-14 |
MySQL Solution
SELECT * FROM Employees
ORDER BY Department ASC, HireDate DESC;
Explanation - MySQL
The ORDER BY clause is used in SQL to sort the output of a SELECT statement. In the above query, we are sorting the data from the Employees table first by the Department column in Ascending order (ASC) and then by the HireDate column in Descending order (DESC). This means that within each department, employees will be listed based on their hire date, with the most recently hired employees at the top.
PostgreSQL Solution
SELECT * FROM Employees
ORDER BY Department ASC, HireDate DESC;
Explanation - PostgreSQL
The ORDER BY clause in PostgreSQL works the same way as it does in MySQL. It allows us to sort the output of a SELECT statement based on one or more columns. In the above query, the data from the Employees table is first sorted by the Department column in Ascending order (ASC) and then by the HireDate column in Descending order (DESC). This results in a list of employees within each department, ordered by their hire date from the most recent to the oldest.