SelectFromData
AnalyticsLesson 4 of 12 · 10 min

LIMIT and Top-N: Just the First Few Rows

"Top 3 products." "Five biggest customers." "Latest 10 orders." Half of all business questions are top-N questions, and they're all the same two-step move: sort with ORDER BY, then cut with LIMIT.

In one line

LIMIT N keeps only the first N rows of the result. Paired with ORDER BY, that's a ranking; without it, it's just some N rows.

The top-N move

Run it for the two highest earners, then change it to LIMIT 3:

Top 2 earners — ORDER BY then LIMIT
Editable · runs in your browser

Read it as the database runs it: take the table → sort by salary, highest first → keep the first 2 rows. The sort happens before the cut — that's what makes it a real "top 2" and not two random rows.

Watch out

LIMIT without ORDER BY is the classic silent bug. It runs fine and returns N rows — just not predictably the ones you meant. If the question contains the word "top", "biggest", "latest", or "first", it needs an ORDER BY.

Where you'll use it constantly

  • Exploring: SELECT * FROM huge_table LIMIT 20 — peek without pulling a million rows.
  • Rankings: top sellers, worst performers, newest signups.
  • Sanity checks: "show me the 5 biggest values in this column — do they look sane?"

Your turn

Return the three highest-paid employees: name and salary, highest first.

Your turn · Exercise

Return the three highest-paid employees: name and salary, highest salary first.

The data

employees

5 rows returned

namesalary
Ada62,000
Bo48,000
Cy71,000
Di52,000
Eli45,000
Runs in your browser
Check yourself

A stakeholder asks for "our 5 biggest orders". Which query actually answers it?


Next: one more small tool for shaping results — DISTINCT, the one-word answer to "what unique values are in this column?"