SQL Top N Rows

ORDER BY + LIMIT, named as the pattern it is — this exact combination answers almost every 'top N' question.

What & Why

"Top 3 highest-spend campaigns," "5 most recent campaign starts," "10 best-selling products" — every one of these is the identical pattern: sort by the relevant column in the right direction, then LIMIT to N.

See How It Works

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
EXAMPLE QUERY
SELECT name, spend FROM marketing.campaigns
ORDER BY spend DESC
LIMIT 3;
RESULT — top 3 campaigns
namespend
Enterprise Search60000.00
Spring Launch55000.00
Finance Retargeting50000.00

The result uses the same Queryflo columns shown in the worked example.

Beginner business practice

Sign up free to try it on a real business scenario