Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to get table row count

Tags:

sql

mysql

count

I currently have a database with over 6 million rows and growing. I currently do SELECT COUNT(id) FROM table; in order to display the number to my users, but the database is getting large and I have no need to store all of those rows except to be able to show the number. Is there a way to select the auto_increment value to display so that I can clear out most of the rows in the database? Using LAST_INSERT_ID() doesn't seem to work.

like image 259
James Simpson Avatar asked Jun 01 '09 04:06

James Simpson


People also ask

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 a 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).

Which is faster count (*) or count 1?

The simple answer is no – there is no difference at all. The COUNT(*) function counts the total rows in the table, including the NULL values.


Video Answer


1 Answers

Following is the most performant way to find the next AUTO_INCREMENT value for a table. This is quick even on databases housing millions of tables, because it does not require querying the potentially large information_schema database.

mysql> SHOW TABLE STATUS LIKE 'table_name'; // Look for the Auto_increment column 

However, if you must retrieve this value in a query, then to the information_schema database you must go.

SELECT `AUTO_INCREMENT` FROM   INFORMATION_SCHEMA.TABLES WHERE  TABLE_SCHEMA = 'DatabaseName' AND    TABLE_NAME   = 'TableName'; 
like image 76
Graham Swan Avatar answered Oct 12 '22 02:10

Graham Swan