DEV Community

Sospeter Mong'are
Sospeter Mong'are

Posted on

1

How to Count the Number of Tables in a Database

When working with databases, you might need to determine the number of tables in a database for various purposes, such as auditing, documentation, or maintenance. Fortunately, most relational database management systems (RDBMS) provide an easy way to count tables using their system catalogs or information schemas. Below, we’ll explore how to do this in commonly used databases.


For PostgreSQL

In PostgreSQL, you can query the information_schema.tables view to count the number of tables within a specific schema:

SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = 'public';
Enter fullscreen mode Exit fullscreen mode
  • Replace 'public' with the schema name you want to query, if different.

For MySQL

In MySQL, you can use the information_schema.tables view and filter by the database name:

SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = 'your_database_name';
Enter fullscreen mode Exit fullscreen mode
  • Replace your_database_name with the name of your database.

For SQL Server

In SQL Server, you can query the sys.tables catalog view to count all the tables in the current database:

SELECT COUNT(*)
FROM sys.tables;
Enter fullscreen mode Exit fullscreen mode
  • This query works for the database you are currently connected to.

For SQLite

In SQLite, you can query the sqlite_master table to count the number of tables:

SELECT COUNT(*)
FROM sqlite_master
WHERE type = 'table';
Enter fullscreen mode Exit fullscreen mode

For Oracle

In Oracle, you can query the all_tables view and filter by the schema owner:

SELECT COUNT(*)
FROM all_tables
WHERE owner = 'YOUR_SCHEMA_NAME';
Enter fullscreen mode Exit fullscreen mode
  • Replace YOUR_SCHEMA_NAME with the appropriate schema name.

Conclusion

Each database has its own way of storing metadata about its structure, but querying the system catalog or information schema is a universal approach to get details about tables. By using these queries, you can quickly count the tables in any database.

Let me know which database you’re using, and I can provide further assistance tailored to your needs!

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay