ORDER BY: Sorting Results
The ORDER BY clause lets you sort the results of your query.
You can sort by one or more columns, in ascending or descending order.
Syntax
SELECT column1, column2 FROM table_name
ORDER BY column1 [ASC|DESC];
- ASC means ascending order (smallest first). This is the default.
- DESC means descending order (largest first).
Example 1: Sort by Age (Ascending)
SELECT name, age FROM employees
WHERE department = 'IT'
ORDER BY age;
Output:
name | age
--------+-----
Mike | 24
Olivia | 25
Emma | 26
Sarah | 28
Bob | 32
Thomas | 33
(6 rows)
This sorts the IT employees from youngest to oldest.
Example 2: Sort by Name (Descending)
SELECT name FROM employees
WHERE department = 'HR'
ORDER BY name DESC;
Output:
name
-------
Anna
Alice
(2 rows)
This sorts names from Z to A.
Example 3: Sort by Department, then Name
SELECT name, department FROM employees
WHERE age > 30
ORDER BY department, name;
Output:
name | department
--------+------------
Grace | Finance
Jack | Finance
Paul | Finance
Bob | IT
Thomas | IT
Tina | Sales
(6 rows)
This sorts by department first. Inside each department, it sorts by name.
Tip: Ties
When two rows have the same value, PostgreSQL does not promise which one comes first. Add a second column to break the tie. For example, ORDER BY age DESC, name puts employees of the same age in alphabetical order.
Also, without ORDER BY, PostgreSQL does not promise any order at all. When the order matters, always use ORDER BY.
You can also sort by a column that is not in your SELECT list. SELECT name FROM employees ORDER BY age; sorts by age but shows only names.
The ORDER BY clause makes results easier to read by putting them in a useful order.
In the exercises, sort the employees by name, and then from oldest to youngest.