Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL get the number of rows in an innodb table

I have a table using innodb. I know the table has roughly 89 million rows. Using

SELECT COUNT(*) FROM table;

takes about five minutes to run. I know that innodb is not optimized for unconditional COUNT(*) queries. How can I restructure the query to give me a count faster? Would just adding WHERE 1=1 work, or do I need to query a specific field?

I know I can get the approximate number of rows using SHOW TABLE STATUS, but I want to get the value in a PHP script, and it seems like there is a lot to dig through using that method.

like image 607
Wige Avatar asked Feb 25 '11 16:02

Wige


People also ask

How do I see the number of rows in a MySQL table?

To counts all of the rows in a table, whether they contain NULL values or not, use COUNT(*). That form of the COUNT() function basically returns the number of rows in a result set returned by a SELECT statement.

How do I count rows in a column in MySQL?

The COUNT() function is an aggregate function that returns the number of rows in a table. The COUNT() function allows you to count all rows or only rows that match a specified condition. The COUNT() function has three forms: COUNT(*) , COUNT(expression) and COUNT(DISTINCT expression) .

How do I count the number of rows in SQL?

Use the COUNT aggregate function to count the number of rows in a table. This function takes the name of the column as its argument (e.g., id ) and returns the number of rows for this particular column in the table (e.g., 5).

What is Rowcount in MySQL?

rowcount. This read-only property returns the number of rows returned for SELECT statements, or the number of rows affected by DML statements such as INSERT or UPDATE . For an example, see Section 10.5.


2 Answers

If you are OK with the estimated number and just don't want to mess with running SHOW TABLE STATUS from PHP, you can use the information_schema DB:

SELECT TABLE_ROWS FROM information_schema.tables
WHERE TABLE_SCHEMA = 'my_db_name' 
AND TABLE_NAME = 'my_table_name';
like image 63
Galz Avatar answered Sep 23 '22 11:09

Galz


If you are ok with approximate number of records, you can use output of "explain".

Simplified verion of the code is

$result = mysql_query('explain SELECT count(*) from TABLE_NAME');
$row = mysql_fetch_assoc($result);
echo $row['rows'];
like image 25
Zimbabao Avatar answered Sep 23 '22 11:09

Zimbabao