For my application most of my SQL queries return a specified number of rows. I’d also like to get the maximum possible number of results i.e. how many rows would be returned if I wasn’t setting a LIMIT.
Is there a more efficient way to do this (using just SQL?) than returning all the results, getting the size of the result set and then splicing the set to return just the first N rows.
You can use
SELECT COUNT(*), but this isn’t ideal for large data sets.A more efficient solution is to use
SQL_CALC_FOUND_ROWSandFOUND_ROWS():http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows
First query:
SELECT SQL_CALC_FOUND_ROWS id, name, etc FROM table LIMIT 10;Second query:
SELECT FOUND_ROWS();You’ll still need two queries, but you run the main query once, saving resources.