VillageSQL is a drop-in replacement for MySQL with extensions.
All examples on this page work on VillageSQL. Install Now →
LIMIT caps how many rows a query returns. It is what you reach for to look at
the top of a large table, and it is the mechanism behind paging through
results.
Open the client with mysql -u root -p sakila before you start.
How LIMIT works
ROW_COUNT with how many rows you want and SKIP_COUNT with how many
to skip first. LIMIT goes last, after ORDER BY. The OFFSET part is
optional.
Examples
1) The first few rows
2) Skip some rows first
3) The 2 number form
MySQL also accepts the offset and the count as a comma separated pair, offset first. It means exactly the same thing.LIMIT ROW_COUNT OFFSET SKIP_COUNT.
LIMIT without ORDER BY asks for arbitrary rows
Drop theORDER BY and the query still runs.
1 warning is nothing to chase. EXPLAIN and EXPLAIN FORMAT=JSON
attach Note 1003, which holds the query as the optimizer rewrote it, and
SHOW WARNINGS prints it.
The key column names idx_title, an index on title that already holds the
column in sorted order, so reading the index is the cheapest way to answer. The
rows arrived sorted as a side effect of that choice. Drop that index, add
another column to the select list, or give the server more data, and the choice
can change with no change to your query.
LIMIT means “any rows” unless ORDER BY says which ones.
Summary
- Use
LIMITto cap how many rows come back. - Add
OFFSETto skip rows before taking them. - Prefer
LIMIT ROW_COUNT OFFSET SKIP_COUNTto the comma form, which reverses the numbers. - Pair
LIMITwithORDER BYevery time, or you have asked for arbitrary rows.
See also
- ORDER BY — deciding which rows LIMIT takes
- Pagination in MySQL — why OFFSET gets slow, and what to use instead
- Reading EXPLAIN in MySQL — the rest of what that plan row means

