Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count table rows

Tags:

mysql

What is the MySQL command to retrieve the count of records in a table?

like image 577
DJ. Avatar asked Dec 12 '09 13:12

DJ.


People also ask

How do I count rows in SQL?

SQL COUNT(), AVG() and SUM() FunctionsThe COUNT() function returns the number of rows that matches a specified criterion.

How do I count rows in a table in Excel?

Just click the column header. The status bar, in the lower-right corner of your Excel window, will tell you the row count. Do the same thing to count columns, but this time click the row selector at the left end of the row. If you select an entire row or column, Excel counts just the cells that contain data.


2 Answers

SELECT COUNT(*) FROM fooTable; 

will count the number of rows in the table.

See the reference manual.

like image 64
Gregory Pakosz Avatar answered Sep 30 '22 11:09

Gregory Pakosz


Because nobody mentioned it:

show table status; 

lists all tables along with some additional information, including estimated rows for each table. This is what phpMyAdmin is using for its database page.

This information is available in MySQL 4, probably in MySQL 3.23 too - long time prior information schema database.

UPDATE:

Because there was down-vote, I want to clarify that the number shown is estimated for InnoDB and TokuDB and it is absolutely correct for MyISAM and Aria (Maria) storage engines.

Per the documentation:

The number of rows. Some storage engines, such as MyISAM, store the exact count. For other storage engines, such as InnoDB, this value is an approximation, and may vary from the actual value by as much as 40% to 50%. In such cases, use SELECT COUNT(*) to obtain an accurate count.

This also is fastest way to see the row count on MySQL, because query like:

select count(*) from table; 

Doing full table scan what could be very expensive operation that might take hours on large high load server. It also increase disk I/O.

The same operation might block the table for inserts and updates - this happen only on exotic storage engines.

InnoDB and TokuDB are OK with table lock, but need full table scan.

like image 34
Nick Avatar answered Sep 30 '22 11:09

Nick