SQL ORDER BY

Sorts the result set by a column — ascending by default, unless told otherwise.

What & Why

ORDER BY sorts the rows a query returns. Without it, a database makes no promise at all about what order rows come back in — ORDER BY is the only way to guarantee a specific sequence.

See How It Works

BUSINESS QUESTION

Sort campaigns by spend, lowest to highest.

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 4
ORDER BY spend
-- unsorted, arrival order
positionnamechannelspend
1Spring Launchgoogle_ads55,000
2Retention Webinaremail45,000
3Finance Retargetinglinkedin50,000
4Enterprise Searchgoogle_ads60,000

Before ORDER BY, row order is not guaranteed.

EXAMPLE QUERY
SELECT name, spend FROM marketing.campaigns
ORDER BY spend;
Now You Try

Practice this concept

Product wants feedback sorted from lowest rating to highest, with the newest feedback first when ratings tie.

Available schema
product

Prefix tables with product.table_name.

user_idratingcreated_at
product.feedback
ColumnType
idinteger
user_idinteger
feature_idinteger
ratinginteger
nps_scoreinteger
commenttext
created_attimestamp with time zone
moderation_buckettext
query.sql
Beginner business practice

Sign up free to try it on a real business scenario