TryBench
Data Analysis & SQL · Foundation lesson 3 of 19

Sorting & Capping with LIMIT

Order query results and cap row counts to find top transactions quickly.

Why this matters

Bosses ask for the top 3 or the biggest. Sorting and limiting gives you that answer without scrolling through everything.

Sort With ORDER BY

ORDER BY sorts the rows. Add DESC for biggest first. ASC, the default, gives smallest first.

In real life: A school ranks pupils by score, highest first. That is ORDER BY score DESC. Sorting by name from A to Z is ORDER BY name ASC.

Keep Only a Few Rows With LIMIT

LIMIT 3 keeps the first 3 rows. It always goes at the very end of the query.

In real life: A top-3 list on a notice board shows only three names, not the whole class. LIMIT 3 cuts the sorted list down in the same way.

SELECT customer_name, amount
FROM orders
ORDER BY amount DESC
LIMIT 3;

Your practice task

Leadership wants to see the top 3 highest-value orders. Select order_id, customer_name, and amount from orders, sorted by amount from highest to lowest, capped at 3 rows.

How to do it

  1. Decide which column decides who is "highest".
  2. Sort the rows so the largest value comes first.
  3. Keep only the first 3 rows.
  4. Press Run proof and read the checklist.

Practice it for free in the app. You get instant checks that show what you got right and what to fix. A lesson takes about two minutes and you can try as many times as you like.

Quick reference: ORDER BY & LIMIT

Retrieves the top N records ranked by a specified metric.

SELECT col
FROM table
ORDER BY col DESC
LIMIT N;

Practice this lesson free

More lessons in this course

See all 19 lessons in Data Analysis & SQL