Menu
Coddy logo textTech

Sort Results Part 2

Part of the Fundamentals section of Coddy's SQL journey — lesson 14 of 72.

When using ORDER BY in SQL, you can sort data by multiple columns.

For example consider the following competition table:

runner_idageavg_speed (m/s)
1473.65
2623.07
3576.82
4564.34
5254.93
6403.94
7236.58
8403.43
SELECT *
FROM competition
WHERE age < 50
ORDER BY age DESC, avg_speed DESC

This query will:

  1. First sort all records by age in descending order (highest to lowest)
  2. If two or more records have the same age, it will then sort those specific records by avg_speed in descending order (highest to lowest)

The result:

runner_idageavg_speed (m/s)
1473.65
6403.94
8403.43
5254.93
7236.58
challenge icon

Challenge

Easy

Available tables and columns:

  • feathers: id, weight, area

Return all of the ids after ordering them by the area in descending order. If the feathers have the same area, sort them by weight in ascending order.

Cheat sheet

You can sort data by multiple columns using ORDER BY. The first column specified takes priority, and subsequent columns are used as tie-breakers:

SELECT *
FROM competition
ORDER BY age DESC, avg_speed DESC

This will:

  1. First sort by age in descending order
  2. If records have the same age, then sort by avg_speed in descending order

Try it yourself

quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals