Home >Database >Mysql Tutorial >How to Count Rows in All MySQL Tables Using a Bash Script
When managing a MySQL database, it’s often useful to get the row counts of all tables to monitor the size and growth of your database. While MySQL doesn’t provide a built-in command to directly count rows across all tables in a database, you can easily achieve this with a simple Bash script.
In this article, we will walk through how to create and run a Bash script that queries each table in a MySQL database and returns the row count (COUNT(1)) for each table.
First, you need to create a Bash script that will connect to your MySQL server, retrieve all the tables, and execute a SELECT COUNT(1) for each table to count the rows. Here's the full script:
#!/bin/bash # MySQL credentials USER="your_username" PASSWORD="your_password" DATABASE="your_database" # Get list of all tables in the database TABLES=$(mysql -u $USER -p$PASSWORD -D $DATABASE -e 'SHOW TABLES;' | tail -n +2) # Loop through each table and get the count for TABLE in $TABLES; do COUNT=$(mysql -u $USER -p$PASSWORD -D $DATABASE -e "SELECT COUNT(1) FROM $TABLE;" | tail -n 1) echo "Table: $TABLE, Count: $COUNT" done
Let’s break down the components of this script: