Pull rows out, then filter them

INPUT · Slides

Just the first few

01 / 04

You do not need all of it

You wanted to know which one sold best, and all six rows came back. Reading that is work. With ten thousand rows it would be worse.

Deciding how many rows come back is LIMIT.

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