Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL count total number of rows

Tags:

mysql

count

I have a complicated MySQL query which takes a lot of time, selecting from a table with more than 150k rows and several JOINS and subqueries. I am limiting the amount of results, but I need to know the total amount of rows.

Is there a way not to repeat the query with COUNT(*) as the field to get them? (repeating the query almost doubles the amount of time the script takes to complete)

like image 320
Gerardo Avatar asked Jan 29 '26 17:01

Gerardo


1 Answers

MySQL has a clause called SQL_CALC_FOUND_ROWS which you put after SELECT and before any field names. Then you call a second query which is just SELECT FOUND_ROWS() AS rows and it gives you how many rows the previous query found.

like image 182
staticsan Avatar answered Feb 01 '26 08:02

staticsan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!