Many people use the following queries to work out the pagination totals. I've seen it on Pixel2Life as well. However, few of us are aware that an
ALL query on a database is bad. This is the process by which MySQL scans the
entire table just to gather all the data. Every single row and possibly every single column.
There is, however, a better way.
SQL_CALC_FOUND_ROWS is 1 of many flags you are able to set at the beginning of the
SELECT query.
Code:
SELECT
SQL_CALC_FOUND_ROWS
myColumn1,
myColumn2
FROM
myTable
LIMIT
0, 10
This will bring back
myColumn1 and
myColumn2 from
myTable, but it will also count the entire amount of items from the table. I'm sure many are aware that any COUNT on a table without any
WHERE clause or
HAVING clause gets the information straight from the table's attached information thus preventing the killer
ALL query.
The aforementioned query will list the first 10 items from your table. However, for the pagination section you will want the total amount of rows to be able to compile the pagination itself. IE:
< Previous - 1, 2, 3, 4, 5 - Next >
Now, as we've used
SQL_CALC_FOUND_ROWS we are able to acquire the total amount of rows regardless of the
LIMIT clause we attached to our earlier query. To get the value from that
SQL_CALC_FOUND_ROWS we use the following MySQL query:
Code:
SELECT FOUND_ROWS();
Therefore, as we limited our query to 0 to 10 columns, we can use the above query to get the total amount of rows. So, if there were 455 rows in our table as reference in the first query, the above query would return 455.
Now how's about that for MySQL optimisation?