Sorting with ORDER BY
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — Introduction to Sorting with ORDER BY
The ORDER BY clause in SQL allows you to sort your query results in a specific order. By default, results from a SELECT query are returned in no particular order.
Here's the basic syntax of ORDER BY:
SELECT column1, column2, ...
FROM table_name
ORDER BY column_name;Let's try sorting our Codémon by their power:
SELECT name, type, power FROM codemon ORDER BY power;By default, ORDER BY sorts in ascending order (smallest to largest, A to Z). Notice how the Codémon are now arranged from lowest power to highest power.
ORDER BY Position in Query
ORDER BY always comes after the FROM clause (and any WHERE clause if present), but before LIMIT if you're using it.
Exercise 2 — Ascending and Descending Order
You can specify the direction of sorting using the keywords ASC (ascending) or DESC (descending):
- ASC: Sorts from smallest to largest or A to Z (default if not specified)
- DESC: Sorts from largest to smallest or Z to A
-- Ascending order (same as default)
SELECT name, level FROM codemon ORDER BY level ASC;Now let's try descending order (highest to lowest):
-- Descending order
SELECT name, level FROM codemon ORDER BY level DESC;You can also sort by text columns. Let's sort Codémons by their names:
-- Alphabetical order (A to Z)
SELECT name, type FROM codemon ORDER BY name ASC;Remember
ASC is optional since it's the default, but it's good practice to include it to make your intentions clear, especially in complex queries.
Sorting NULL values
In SQLite, NULL is treated as smaller than any other value when sorting. So rows with NULL come first with ASC and last with DESC. (Not every database agrees: PostgreSQL does the opposite.)
Exercise 3 — Default Sorting Order
If you don't specify ASC or DESC in an ORDER BY clause, what is the default sorting behavior?
Hint : Think about what happens when you simply write ORDER BY without any additional keywords.
Exercise 4 — Sorting by Multiple Columns
You can sort by multiple columns in SQL by listing them in the ORDER BY clause, separated by commas. The sorting priority follows the order of the columns listed.
The database will first sort by the first column. If there are ties (same values), it will then sort by the second column, and so on.
SELECT name, level, power FROM codemon ORDER BY level, power DESC;In this example, the results are first sorted by level (ascending), and then within each level, Codémons are sorted by power in descending order.
You can also specify different sort directions for each column:
SELECT name, level, power FROM codemon ORDER BY level DESC, power ASC;Real-World Application
Multi-column sorting is useful for scenarios like leaderboards (sort by score DESC, then by time ASC) or contact lists (sort by last name, then by first name).
Exercise 5 — Complete the Multi-Column Sorting
Complete the SQL query to sort Codémons first by their type in alphabetical order, and then by their power in descending order (highest power first).
Hint : Consider which column should be sorted first and which should be sorted second. Also think about which direction (ASC or DESC) is needed for each column.
Exercise 6 — Combining ORDER BY with WHERE
You can combine ORDER BY with WHERE to filter records first and then sort the filtered results. This is a common pattern in SQL queries.
The correct order of clauses is:
SELECT columns
FROM table
WHERE condition
ORDER BY columnsLet's see an example where we filter Codémons with power greater than 70 and then sort them by their level in descending order.
SELECT name, type, power, level
FROM codemon
WHERE power > 70
ORDER BY level DESC;As we saw in the previous lessons, you can add multiple conditions in the WHERE clause and still use ORDER BY:
SELECT name, type, power
FROM codemon
WHERE type = 'water' OR type = 'electric'
ORDER BY power DESC;Order of Operations
Always remember that WHERE is processed before ORDER BY. The database first filters the data, then sorts the filtered results.
Exercise 7 — Query with Filtering and Sorting
Which query would return the names of all Codémons with level greater than 15, sorted alphabetically by name?
SELECT name FROM codemon WHERE level > 15 ORDER BY name ASC;SELECT name FROM codemon ORDER BY name ASC WHERE level > 15;SELECT name FROM codemon WHERE name = name AND level > 15;SELECT name ORDER BY name ASC FROM codemon WHERE level > 15;Hint : Remember the correct order of SQL clauses in a query: SELECT, FROM, WHERE, then ORDER BY.
Exercise 8 — Column Positions in ORDER BY
In addition to using column names, you can also sort by column position in the ORDER BY clause. Given the following query, what would happen?
SELECT name, power, level FROM codemon ORDER BY 2 DESC;Hint : In ORDER BY, you can use numbers to refer to columns by their position in the SELECT list (starting from 1). Consider which column is in position 2 in this query.
Exercise 9 — Find the Most Powerful Codémons by Type
Complete the SQL query to find all fire and water type Codémons, sorted by their power in descending order.
Hint : You need to correctly specify the types to filter for, the ORDER BY clause, and the direction of sorting.
Exercise 10 — Sorting Expressions and Results
Match each ORDER BY expression with its correct sorting result:
ORDER BY name ASCORDER BY power DESCORDER BY type, level ASCORDER BY captured_date DESCExercise 11 — SQL Clause Execution Order
What is the correct order of execution for these SQL clauses?
We are talking about EXECUTION order, not the order they appear in the query!
Hint : Understanding the actual execution order of SQL clauses is important for writing effective queries. Think about what must happen first logically.
Exercise 12 — Ranking the squad
Professor Pi wants the squad listed by experience, and when two Codémons share the same level, the weaker one should come first.
Write a query that returns the name, level and power of every Codémon, sorted by level descending, then by power ascending.
-- Write your query below