Get record counts for all tables in MySQL database
Looking for a summary of row counts for all tables in your MySQL database? Run this nifty SQL snippet:
This chunk of code pulls a summary directly from INFORMATION_SCHEMA, revealing both the table_name and the estimated TABLE_ROWS for each table in 'your_db_name'.
Obtaining precise row count: The COUNT(*)
method
While the snippet above gets you there quick, it's an estimate. If you're dealing with InnoDB tables, TABLE_ROWS
will give you an approximation, not the precise count.
Want exact numbers? Run a COUNT(*)
on each table individually:
Adding up all rows: Ultimate row summation with SUM(TABLE_ROWS)
Who doesn't like the big totals? Aggregate all your rows across all tables with this:
MySQL quirks: Precision varies
Accuracy can be a tricky beast: different storage engines and versions handle TABLE_ROWS
differently. For instance, InnoDB doesn't count rows exactly. And some MySQL versions might throw guesses left and right.
Verification for precision lovers
Want to make sure no TABLE_ROWS
estimation is fooling you? Especially when it's mission-critical? Enter the verifier:
Organised for efficiency: Sorting by TABLE_ROWS
Let's say you want to know the most burgeoning tables fast. Simply modify the query to order by TABLE_ROWS
:
Pro moves: Advanced techniques and considerations
After sifting through the basics, let's explore some pro moves and tricks to augment our capabilities.
Playing with multiple databases: Dynamic SQL
Got more than one database to check? Craft dynamic SQL:
This will produce an array of SQL SELECT
statements which can then provide row counts from all your desired schemas.
Automation is not absolute
While our dynamic SQL script makes work easier, it merely generates queries and does not execute them. Also, be careful while concatenating the output, as the final UNION may cause syntax errors.
Watch your MySQL version
The devil is in the detail: The accuracy of INFORMATION_SCHEMA.TABLES
can vary between versions, affecting your row count.
Was this article helpful?