Thursday, June 21, 2007

How to get number of rows in MySQL while using LIMIT cause

Normally, in MySQL, if you want to get number of rows to render page list while limit the output to pages, you would have to execute them as two queries like these:

SELECT COUNT(*) FROM foo WHERE bar = 1
SELECT * FROM foo WHERE bar = 1 LIMIT 15


However, I was curious about how to optimize this process. I think there must be a better way that I can count the number of rows that matching my condition and limiting number of rows returned at the same time.

After I google a bit, I found the answer using SQL_CALC_FOUND_ROWS. I think this is better than the above example.

SELECT SQL_CALC_FOUND_ROWS * FROM foo WHERE bar = 1 LIMIT 15
SELECT FOUND_ROWS();


Thanks Array Studio Workshop for this wonderful tip!

No comments: