Introduction To SQL_CALC_FOUND_ROWS and Found_Rows()
In Mysql there are lot of built in functions which can be used to easily manipulate mysql results. But we tend to write lot of queries and code to do those tasks due to lesser knowledge in those built in functions. In this post I am going to explain a mysql function which needs to be used in lot of practical situations. Lets start learning Found_Rows function.
In web applications we write lot of queries which uses the Mysql LIMIT statement to limit the results from database. This is effective since getting the full record set would take lot of time and memory in server. So In some situation although we limit the query to a certain value, we may need to find the actual row count returned from query if the LIMIT statement is not available. So Mysql Found_Rows() can be used in combination with SQL_CALC_FOUND_ROWS to get the actual number of rows returned from a query.
Why We Need Found_Rows Function
In web applications we write lot of queries which uses the Mysql LIMIT statement to limit the results from database. This is effective since getting the full record set would take lot of time and memory in server. So In some situation although we limit the query to a certain value, we may need to find the actual row count returned from query if the LIMIT statement is not available. So Mysql Found_Rows() can be used in combination with SQL_CALC_FOUND_ROWS to get the actual number of rows returned from a query.
How To Use Found_Rows Function
$sql = mysql_query("Select SQL_CALC_FOUND_ROWS * from students where marks > 75 LIMIT 10"); $actual_row_count = mysql_query("Select Found_Rows()"); print_R(mysql_fetch_object($actual_row_count));
Code Explanation
- First we run the original query with limit statement and SQL_CALC_FOUND_ROWS.
- It will return all the columns and 10 rows of the students table.
- Then we run the Found_Rows functions as a query to get the actual row count
- This is much faster than running the same query with and without limit satement twice.
Practical Usage
- In pagination we limit the query results. But we need to get the actual row count to display the number of pages in pagination. Normally we run the query twice. Use this method in pagination to improve performence.
- Assume a situation where we get the top 10 students with highest marks. What happens if the 11th student has the same marks as 10. In such case that student will not be selected.Hence it is important to count the total rows even if we want to limit the results for better decision making.
Leave a Reply