Question

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?

Was it helpful?

Solution

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!

OTHER TIPS

Use limit - you don't want to transfer masses of data from the database to the scripting engine if you can avoid it.

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.

You can use some existing libraries to help you:

Pear::Pager can help with the output, and to limit the database traffic to only what you need, you can use a wrapper provided in the examples that come with it.

Here's a tutorial I just googled that has it all...

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top