Module 5 · SQL for Data Analysis
ORDER BY
Sort results by one or more columns, in ascending or descending order.
About 20 minutes
The problem
Finance is reviewing the most valuable bookings from the first week of January 2026. They want the biggest charges at the top, so they can check those first.
Operations wants the routes listed from the longest journey to the shortest, to plan staffing for long-haul shipments.
A database doesn't promise to return rows in any particular order. If order matters, you have to ask for it.
The concept
ORDER BY sorts the result. It comes after WHERE.
ASCsorts smallest to largest, A to Z, earliest to latest. It's the default, so you can leave it out.DESCsorts largest to smallest, Z to A, latest to earliest.- You can sort by several columns. The second column only decides the order when the first column has a tie.
The order of the clauses you've learned so far is always:
SQL
SELECT … FROM … WHERE … ORDER BY …Example
SELECT shipment_id, booking_date, freight_charge
FROM shipments
WHERE booking_date BETWEEN '2026-01-01' AND '2026-01-07'
ORDER BY freight_charge DESC;Walkthrough
WHEREfirst narrows the data down to the first week of January 2026.ORDER BY freight_charge DESCthen puts the most expensive shipment first.
Now sort by two columns: routes by mode, and within each mode, longest journeys first.
SELECT origin, destination, mode, target_transit_days
FROM routes
ORDER BY mode, target_transit_days DESC;mode sorts A to Z (Air, Road, Sea). Inside each mode, target_transit_days DESC puts the longest routes first. Each column in ORDER BY has its own direction.
Practice
Practice
List every route's origin, destination and target_transit_days, from the longest journey to the shortest. Where two routes take the same number of days, put the lower route_id first.
Ctrl + Enter to run. Tab indents; press Esc then Tab to leave the editor.
Challenge
Challenge · optional
Show company_name and signup_date for customers in Lagos, newest customers first. If two signed up on the same day, sort them by company_name A to Z.
Ctrl + Enter to run. Tab indents; press Esc then Tab to leave the editor.
Check your understanding
Answer every question to check.