Learn SQL/Beginner/Sorting & Limiting/SQL Sorting by Multiple Columns

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.

idnamechannelspendstart_dateend_datestatustarget_segment
1Spring Launchgoogle_ads55000.002024-01-152024-03-31activesmb
2Retention Webinaremail45000.002024-02-102024-04-15activeenterprise
3Finance Retargetinglinkedin50000.002024-03-122024-05-31activeenterprise
4Enterprise Searchgoogle_ads60000.002024-04-012024-06-30activeenterprise
Watch the rows sort into placeStep 1 of 3
ORDER BY channel ASC, spend DESC
-- unsorted, arrival order
positionnamechannelspend
1Spring Launchgoogle_ads55,000
2Retention Webinaremail45,000
3Finance Retargetinglinkedin50,000
4Enterprise Searchgoogle_ads60,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
marketing

Prefix tables with marketing.table_name.

idsourcecountrylead_scorecreated_at
marketing.leads
ColumnType
idinteger
campaign_idinteger
emailtext
created_attimestamp with time zone
qualified_attimestamp with time zone
converted_attimestamp with time zone
lead_scoreinteger
sourcetext
countrytext
archive_statustext
query.sql
Beginner business practice

Sign up free to try it on a real business scenario