Home > Database > Mysql Tutorial > How to Count Rows in All MySQL Tables Using a Bash Script

How to Count Rows in All MySQL Tables Using a Bash Script

DDD
Release: 2024-11-25 16:00:15
Original
288 people have browsed it

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.

Prerequisites

  • MySQL Server: You must have a running MySQL server with access to the database.
  • Bash: The script will be written in Bash, so make sure you’re running it on a Unix-like system (Linux/macOS) with Bash available.

Step-by-Step Guide

1. Create the Bash Script

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
Copy after login

2. Script Breakdown

Let’s break down the components of this script: