Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql SQL_CALC_FOUND_ROWS and pagination

So I have a table that has a little over 5 million rows. When I use SQL_CALC_FOUND_ROWS the query just hangs forever. When I take it out the query executes within a second withe LIMIT ,25. My question is for pagination reasons is there an alternative to getting the number of total rows?

like image 748
John Avatar asked Jan 22 '11 03:01

John


People also ask

What is Sql_calc_found_rows in MySQL?

MySQL has a nonstandard query modifier called SQL_CALC_FOUND_ROWS. When in use on a SELECT with LIMIT, it attempts to calculate how many rows would have been returned if the limit were not there, and then store that for later retrieval in FOUND_ROWS().

Why use SQL_ CALC_ FOUND_ ROWS?

SQL_CALC_FOUND_ROWS and FOUND_ROWS() can be useful in situations when you want to restrict the number of rows that a query returns, but also determine the number of rows in the full result set without running the query again.

What is MySQL pagination?

It is used to view a specific number of rows; for example, in a query output, you want to see the records between 10 and 20, then you can use OFFSET. It populates all the records of the table, and it discards the previous records that are defined in the OFFSET clause.


1 Answers

SQL_CALC_FOUND_ROWS forces MySQL to scan for ALL matching rows, even if they'd never get fetched. Internally it amounts to the same query being executed without the LIMIT clause.

If the filtering you're doing via WHERE isn't too crazy, you could calculate and cache various types of filters to save the full-scan load imposed by calc_found_rows. Basically run a "select count(*) from ... where ...." for most possible where clauses.

Otherwise, you could go Google-style and just spit out some page numbers that occasionally have no relation whatsoever with reality (You know, you see "Goooooooooooogle", get to page 3, and suddenly run out of results).

like image 190
Marc B Avatar answered Sep 20 '22 15:09

Marc B