SQL Sorting by Multiple Columns
A second column breaks ties left by the first — sorted within each group formed by the first column.
What & Why
List more than one column in ORDER BY, separated by commas. Rows sort by the first column, and whenever two rows tie on it, the second column breaks the tie.
See How It Works
BUSINESS QUESTION
Sort by channel, then by spend (highest first) within each channel.
| id | name | channel | spend | start_date | end_date | status | target_segment |
|---|---|---|---|---|---|---|---|
| 1 | Spring Launch | google_ads | 55000.00 | 2024-01-15 | 2024-03-31 | active | smb |
| 2 | Retention Webinar | 45000.00 | 2024-02-10 | 2024-04-15 | active | enterprise | |
| 3 | Finance Retargeting | 50000.00 | 2024-03-12 | 2024-05-31 | active | enterprise | |
| 4 | Enterprise Search | google_ads | 60000.00 | 2024-04-01 | 2024-06-30 | active | enterprise |
Watch the rows sort into placeStep 1 of 3
ORDER BY channel ASC, spend DESC
-- unsorted, arrival order| position | name | channel | spend |
|---|---|---|---|
| 1 | Spring Launch | google_ads | 55,000 |
| 2 | Retention Webinar | 45,000 | |
| 3 | Finance Retargeting | 50,000 | |
| 4 | Enterprise Search | google_ads | 60,000 |
Before ORDER BY, the rows remain in their incoming order.
EXAMPLE QUERY
SELECT name, channel, spend FROM marketing.campaigns
ORDER BY channel ASC, spend DESC;Now You Try
Practice this concept
Marketing wants leads sorted by highest score, then newest creation time, with id as the final tie-breaker.
Available schema
marketingPrefix tables with marketing.table_name.
idsourcecountrylead_scorecreated_atmarketing.leads| Column | Type |
|---|---|
| id | integer |
| campaign_id | integer |
| text | |
| created_at | timestamp with time zone |
| qualified_at | timestamp with time zone |
| converted_at | timestamp with time zone |
| lead_score | integer |
| source | text |
| country | text |
| archive_status | text |
query.sql
Sign up free to try it on a real business scenario