79

I have a SQL Server 2012 database called MyDatabase. How can I find how many tables are in the database?

I'm assuming the format of the query would be something like the following, but I don't know what to replace database_tables with:

USE MyDatabase
SELECT COUNT(*)
FROM [database_tables]
Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
Tot Zam
  • 8,406
  • 10
  • 51
  • 76
  • 3
    @TabAlleman how could this possibly be a duplicate of that? Tables and stored procs are different things and so SQL 2008 and 2012 are not the same either. – Alan Burstein Aug 02 '17 at 16:29

3 Answers3

149

You can use INFORMATION_SCHEMA.TABLES to retrieve information about your database tables.

As mentioned in the Microsoft Tables Documentation:

INFORMATION_SCHEMA.TABLES returns one row for each table in the current database for which the current user has permissions.

The following query, therefore, will return the number of tables in the specified database:

USE MyDatabase
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'

As of SQL Server 2008, you can also use sys.tables to count the the number of tables.

From the Microsoft sys.tables Documentation:

sys.tables returns a row for each user table in SQL Server.

The following query will also return the number of table in your database:

SELECT COUNT(*)
FROM sys.tables
Tot Zam
  • 8,406
  • 10
  • 51
  • 76
  • 1
    A good article on the two sources is this one [The case against INFORMATION_SCHEMA views](https://sqlblog.org/2011/11/03/the-case-against-information_schema-views), and highlights a few reasons why you might use the system catalog over the INFORMATION_SCHEMA. Also, it is pedantic I know, but `sys.tables` was introduced in SQL Server 2005 – GarethD Aug 02 '17 at 15:16
  • @GarethD link is broken – Bob the Builder Sep 06 '22 at 19:04
  • @BobtheBuilder https://sqlblog.org/2011/11/03/the-case-against-information_schema-views – GarethD Sep 07 '22 at 08:45
25
USE MyDatabase
SELECT Count(*)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE';

to get table counts

SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = 'dbName';

this also works

USE databasename;
SHOW TABLES;
SELECT FOUND_ROWS();
Tot Zam
  • 8,406
  • 10
  • 51
  • 76
Shafeer khan
  • 464
  • 5
  • 8
7

Try this:

SELECT Count(*)
FROM <DATABASE_NAME>.INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
Tot Zam
  • 8,406
  • 10
  • 51
  • 76
M84
  • 727
  • 6
  • 14