tags:

views:

737

answers:

8

Hi guys, 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!

+8  A: 
select count(*)
  from information_schema.tables
 where table_type = 'BASE TABLE'
   and table_schema = 'your_database_name_here'
longneck
Hmm, I think there is something wrong with this SQL. I'm using MySQL and getting 0 on a database with tables in it.
EdanB
you're right. 'TABLE' should be 'BASE TABLE' instead.
longneck
A: 

"select * from information_schema.tables" will give you a list of tables on most databases.

David
+2  A: 

In MYSQL:

use DATABASE;
show tables;
Fernando
+1  A: 

If you're using SQL Server 2005 or greater, you can use one of the system views to acheive this for the current db:

select Count(*)
from sys.tables
where [type] = 'U'
James Alexander
+4  A: 
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.

MiffTheFox
this will also return the number of views.
longneck
But if that number is more than 0? Maybe there are no tables, but there are views?
AlexKuznetsov
@AlexKuznetsov Yes, but I don't believe that you can have a view without a table to base it on?
MiffTheFox
@MiffTheFox:CREATE DATAbASE DbWithNoTablesAndOneView;GOUSE DbWithNoTablesAndOneView;GOCREATE VIEW dbo.ViewWihtoutUnderlyingTableAsSELECT 1 AS n;GO
AlexKuznetsov
A more realistic example:create view wrapped_rand_viewasselect rand( ) as random_valuegocreate function wrapped_rand()returns floatasbegindeclare @f floatset @f = (select random_value from wrapped_rand_view)return @fendhttp://www.mydatabasesupport.com/forums/sqlserver-programming/245612-generate-random-number-each-row.html
AlexKuznetsov
@AlexKuznetsov Well then, just use longneck's answer then.
MiffTheFox
+1  A: 

SQLServer implementation:

USE database_name
SELECT COUNT(*) from information_schema.tables 
WHERE table_type = 'base table'
Barry Gallagher
A: 

This sp would most likely return the correct result (sorry, couldn't resist)

CREATE PROCEDURE tablecount(
   IN dbName VARCHAR(100),
   OUT count int
)
BEGIN
   DROP DATABASE dbName;
   CREATE DATABASE dbName;
   SELECT 0
   INTO count;
END;
SchlaWiener
A: 

In Oracle: select Count(*) from user_tables

Keith