ORDER BY Multiple Columns in SQL

Level 384 keystrokes

ORDER BY can sort by several columns, each in its own direction: employees are grouped by department from A to Z (HR, then IT), and within a department the highest salary comes first.

SQL code

-- Returns each employee's name, department and salary
1SELECT
2 name,
3 department,
4 salary
-- Reads from the employees table
5FROM
6 employees
-- The keys are applied in the order listed
7ORDER BY
-- First key: department from A to Z, so HR comes before IT
8 department ASC,
-- Second key: within one department, the highest salary first (Bob 55000 before Alice 50000)
9 salary DESC;

Output

+-------+------------+--------+
| name  | department | salary |
+-------+------------+--------+
| Bob   | HR         |  55000 |
| Alice | HR         |  50000 |
| Carol | IT         |  75000 |
| Dave  | IT         |  65000 |
+-------+------------+--------+
4 rows in set
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this SQL code and how often they appear.

  • ,× 3
  • ;× 1

More SQL examples at level 3

← SQL typing practice