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
- Sorting with ORDER BY
- Sorting by Multiple Columns
- LIMIT and OFFSET
- Finding Top-N Records