I need to check if a database is totally empty (no tables) using an SQL query. How can this be done?
Thanks for the help!
I needed something that would give me an exit code to use in Bash. This builds off of @longneck's solid answer. If the database has tables, the select
statement will set the contents
column as "has tables". Grep will return a successful 0
in this case, otherwise it will return a non-zero.
#!/bin/bash
user=username
pw=passwd
db=database
mysql -u ${user} -p"${pw}" -D ${db} --execute="SELECT CASE COUNT(*) WHEN '0' THEN 'empty database' ELSE 'has tables' END AS contents FROM information_schema.tables WHERE table_type = 'BASE TABLE' AND table_schema = '${db}';" | grep 'has tables'
echo $?