SQL to check if database is empty (no tables)

前端 未结 11 1333
后悔当初
后悔当初 2021-02-14 04:59

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!

相关标签:
11条回答
  • 2021-02-14 05:31

    Solution: In order to verify your databases is not empty you can watch list of tables and measure instances in it.

    first: perform simple connection to your db mysql -u <userName> -p ,run show databases; pick your database using use <databaseName>; and then run show tables; and expect to have list of tables.

    +----------------------------------------+
    | Tables_in_databaseName                 |
    +----------------------------------------+
    | databaseA                              |
    | databaseB                              |
    | databaseC                              |
    +----------------------------------------+
    

    Second: Perform simple count action on primary key / main table on sql and count instances:

    select count(*) from <primaryKeyColumn>;
    

    count result should be > 0

    +----------+
    | count(*) |
    +----------+
    |   100    |
    +----------+
    
    0 讨论(0)
  • 2021-02-14 05:40

    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 $?
    
    0 讨论(0)
  • 2021-02-14 05:47
    SELECT COUNT(DISTINCT `table_name`) FROM `information_schema`.`columns` WHERE `table_schema` = 'your_db_name'
    

    will return the actual number of tables (or views) in your DB. If that number is 0, then there are no tables.

    0 讨论(0)
  • 2021-02-14 05:49
    select count(*)
      from information_schema.tables
     where table_type = 'BASE TABLE'
       and table_schema = 'your_database_name_here'
    
    0 讨论(0)
  • 2021-02-14 05:51

    In bash:

    db_name='my_db'
    mysql -s --skip-column-names -e "SELECT COUNT(DISTINCT table_name) FROM information_schema.columns WHERE table_schema = '$db_name'"
    
    0 讨论(0)
提交回复
热议问题