Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: How to efficiently count the number of rows in a large table?

Tags:

mysql

What is the way to most efficiently count the total number of rows in a large table? I have a table with 23 million rows and the following query takes 30+ seconds on production hardware:

select count(*) from tablename;

It seems that MySQL must be doing a table scan, but it doesn't seem like this should be necessary.

like image 987
Landon Kuhn Avatar asked Jul 14 '11 20:07

Landon Kuhn


People also ask

How do I count the number of rows in MySQL?

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.

What is the method to count the number of rows in a table?

The SQL COUNT( ) function is used to return the number of rows in a table. It is used with the Select( ) statement.

What is the most performant way to get total number of records from table?

The best way to get the record count is to use the sys. dm_db_partition_stats or sys. partitions system views (there is also sysindexes, but it has been left for the backward compatibility with SQL Server 2000).


1 Answers

If an approximation is enough, you can use:

show table status like 'tablename'
like image 153
tsg Avatar answered Oct 02 '22 12:10

tsg