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.
| 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 4
ORDER BY spend
-- 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, 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
productPrefix tables with product.table_name.
user_idratingcreated_atproduct.feedback| Column | Type |
|---|---|
| id | integer |
| user_id | integer |
| feature_id | integer |
| rating | integer |
| nps_score | integer |
| comment | text |
| created_at | timestamp with time zone |
| moderation_bucket | text |
query.sql
Sign up free to try it on a real business scenario