MySQL & PHP – SQL_CALC_FOUND_ROWS – An easy way to get the total number of rows regardless of LIMIT

Here is a little trick I found awhile back. I faced a challenge several months ago where I had to query a large, complex data result from MySQL. I "paged" through the results using LIMIT and OFFSET. However, I wanted to know the total number of rows w/o the LIMIT. The previous coder accomplished this by a query before appending the LIMIT statement at the end. This turned out to be very inefficient due to MySQL put together the 10000+ rows and sent it to PHP ready to be parsed, only to have the function mysql_num_rows() to be executed on it.

Instead I found on the internet (and I lost the link to the article) the MySQL trick "SQL_CALC_FOUND_ROWS." I believe MySQL 4 and 5 support it. It allows you to place "SQL_CALC_FOUND_ROWS" right after the SELECT statement. Example:

MySQL:
  1. SELECT SQL_CALC_FOUND_ROWS * FROM users LIMIT 0, 10

This tells MySQL to store a total number of rows that would have been returned regardless of the LIMIT statement. You retrieve this result but calling this query immediately after:

MySQL:
  1. SELECT FOUND_ROWS() AS `found_rows`;

So, in PHP you could do the following code:


PHP:
  1. // ...
  2. $sql = "SELECT SQL_CAL_FOUND_ROWS  * FROM users LIMIT 0, 10";
  3. $result = mysql_query($sql);
  4. $sql = "SELECT FOUND_ROWS() AS `found_rows`;";
  5. $rows = mysql_query($sql);
  6. $rows = mysql_fetch_assoc($rows);
  7. $total_rows = $rows['found_rows'];
  8. // ...

There is also a trick that if you want to insert SQL_CALC_FOUND_ROWS into the statement by the following PHP code:


PHP:
  1. // ...
  2. $sql = trim($sql);
  3. $exploded = explode(" ", $sql);
  4. $exploded[0] .= " SQL_CALC_FOUND_ROWS ";
  5. $sql = implode(" ", $exploded);
  6. // ...

Hopefully this can help someone looking to optimize their queries while not loosing functionality.

Related Posts

  1. My 2009 Technology Recap Its been two years now that I've been a more or less "serious blogger." I had using the term blogger, since when people hear about blogs, they think of people either detailing their entire lives, or pumping some angel. For me, blogging has just been a way to share information...
  2. Presentation: Real Life Scaling Here are my slides for the presentation that I gave at the Utah Open Source Conference on Friday. It was an awesome conference, and I am glad that I was able to be involved. Real Life Scaling: A Tale of Two Websites View more presentations from Justin Carmony. If you...

Posted in General. Tagged with , , , , , , .

0 Responses

Comments RSS Feed.

Some HTML is OK

(required)

(required, but never shared)

or, reply to this post via trackback.

Powered by WP Hashcash