I need to display many pages of news in a site.
Should i do the pagination in the db query using limit or do it in my php script after getting all the results?
views:
631answers:
7Use limit - you don't want to transfer masses of data from the database to the scripting engine if you can avoid it.
Personally, I would use the query to do it. Obviously, that can change if your dealing with AJAX and such, but just doing a basic limit in the query and outputting the results is simple and efficient.
Use limit in SQL! Every time!
Otherwise you're throwing around considerably more data than you need to, which makes your scripts unnecessarily slow, and will lead to scalability problems as the amount of data in your tables increases.
Limit is your friend!
If you want only work with a DBMS that support this than do it on the DBMS. If you want support other DBMS in the future then ad a layer between that can handle depending on the current DBMS.
In addition to using LIMIT
, I'd suggest using an explicit WHERE
clause to set the offset, and order the results on that column. For example:
--- First page (showing first 50 records)
SELECT * FROM people ORDER BY id LIMIT 50
--- Second page
SELECT * FROM people WHERE id > 50 ORDER BY id LIMIT 50
This further limits the numbers of rows returned to those within the desired range. Using the WHERE
approach (as opposed to a LIMIT
clause with a separate offset, e.g. LIMIT 50,50
) allows you to deal effectively with paging through records with other natural keys, e.g. alphabetically by name, or by date order.