MySQL Limit
The LIMIT clause restricts how many rows a query returns, which is essential for paging through large result sets and for quickly inspecting sample data.
The LIMIT Clause
LIMIT is added at the end of a SELECT statement to cap the number of rows returned, regardless of how many rows actually match the query's conditions. This is especially useful for exploring a large table without pulling back millions of rows, or for building 'top N' style reports.
Basic LIMIT syntax
SELECT column1, column2
FROM table_name
LIMIT number_of_rows;Selecting the Top N Rows
LIMIT is most powerful when combined with ORDER BY, since without a defined sort order, the rows returned by LIMIT are not guaranteed to be in any particular order. To reliably get the three most expensive products, you must sort first and then limit.
Get the 3 most expensive products
SELECT ProductName, Price
FROM Products
ORDER BY Price DESC
LIMIT 3;Paging Through Results With OFFSET
The OFFSET keyword tells MySQL to skip a given number of rows before it starts returning results, which is the basis of pagination in web applications — for example showing 'page 2' of a product listing.
Skip the first 10 rows, then return the next 10 (page 2)
SELECT ProductName, Price
FROM Products
ORDER BY ProductID
LIMIT 10 OFFSET 10;The Shorthand LIMIT offset, count Syntax
MySQL also supports a comma-separated shorthand for LIMIT, where the first number is the offset and the second number is the row count. Both forms are equivalent, so use whichever reads more clearly to your team.
Equivalent shorthand for LIMIT ... OFFSET ...
SELECT ProductName, Price
FROM Products
ORDER BY ProductID
LIMIT 10, 10;- LIMIT caps the number of rows returned by a query
- OFFSET skips a number of rows before starting to return results
- Always pair LIMIT with ORDER BY for deterministic 'top N' results
- The shorthand LIMIT offset, count is MySQL-specific and not standard SQL
Exercise: MySQL Limit
What does the LIMIT clause control in a query?