SQL LIMIT

Caps how many rows come back — almost always paired with ORDER BY to mean something specific.

What & Why

LIMIT n returns at most n rows. On its own it just truncates whatever order the rows happened to arrive in — paired with ORDER BY first, it becomes "top N."

See How It Works

BUSINESS QUESTION

The two highest-spend campaigns.

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
Sort first, then cut off at 2Step 1 of 2
ORDER BY spend DESC LIMIT 2
-- ORDER BY spend DESC (no LIMIT yet)
positionnamechannelspend
1Enterprise Searchgoogle_ads60,000
2Spring Launchgoogle_ads55,000
3Finance Retargetinglinkedin50,000
4Retention Webinaremail45,000

The campaigns are sorted by spend, highest first.

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

Practice this concept

Product wants the 5 lowest-rated feedback records for a quick quality review.

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