Limiting Query Results

Another SQL term you can add to your query statement is LIMIT. Unlike WHERE, which affects which records to return, or ORDER BY, which decides how those records are sorted, LIMIT states how many records to return. It is used like so:

SELECT * FROM tablename LIMIT 10;
SELECT * FROM tablename LIMIT 10, 20;

In the first example, only the initial ten records from the query will be returned. In the second, 20 records will be returned, starting with the 11th. Like arrays in PHP, the indexes in databases begin at 0 when it comes to LIMITs, so 10 is the 11th record.

You can use LIMIT with WHERE and/or ORDER BY, appending it to the end of your query.

 SELECT * FROM users WHERE last_name = 'Simpson' ORDER BY registration_date ...

Get PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.