01 / 04
Pull rows out, then filter them
INPUT · Slides
Just the first few
02 / 04
How LIMIT looks
Write LIMIT n at the very end of a query and you get that many rows.
Which rows depends on the order. If you have not said, you get them from the top in the order they went into the table.
SELECT name, price FROM booths LIMIT 3;Result
cotton candy | 150 grilled squid | 400 fruit juice | 120
03 / 04
Put it with ORDER BY
LIMIT really earns its keep next to ORDER BY. Sort first, take a few from the top, and you have a top three.
The writing order is WHERE, then ORDER BY, then LIMIT. LIMIT is always last.
SELECT name, sold FROM booths ORDER BY sold DESC LIMIT 3;Result
fruit juice | 140 shaved ice | 118 grilled noodles | 97
04 / 04
Taking exactly one
LIMIT 1 hands back "the most whatever it is" as a single row. It is the standard way to ask for a best score or a lowest price.
Asking for more rows than exist is not an error either — you just get what there is. Let us write some.
SELECT name, price FROM booths ORDER BY price DESC LIMIT 1;Result
grilled squid | 400