0Pricing
SQL Academy · Lesson

Finding Top-N Records

Get the highest and lowest values.

What Is a Top-N Query

A Top-N query answers questions like "the 3 most expensive products", "the 10 newest orders" or "the lowest 5 scores".

It's just sorting plus a limit, but it's so common it deserves a name.

-- Top 3 most expensive products
SELECT name, price
FROM products
ORDER BY price DESC
LIMIT 3;

Bottom-N Records

For the smallest values, flip the direction. Sort ASC and take the first N to get the cheapest, oldest or lowest rows.

-- 5 cheapest products
SELECT name, price
FROM products
ORDER BY price ASC
LIMIT 5;

All lessons in this course

  1. Sorting with ORDER BY
  2. Sorting by Multiple Columns
  3. LIMIT and OFFSET
  4. Finding Top-N Records
← Back to SQL Academy