MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

What is the use of information_schema database in mysql

information_schema is MySQL's built-in, read-only catalog of metadata. You query it with ordinary SQL to find out which databases, tables, columns, indexes, constraints, routines and privileges exist on a server. This page explains how it works in MySQL 8.0 and later and gives runnable queries for common DBA and DevOps tasks, such as measuring table sizes, finding tables without primary keys and generating migration scripts.

The information_schema database in MySQL is a virtual database that provides metadata about the database system, such as information about the database, tables, columns, and indexes.

The information_schema database contains several read-only tables that contain information about the database system, including:

  1. SCHEMATA: Information about the databases available in the current MySQL server.
  2. TABLES: Information about the tables in the current database.
  3. COLUMNS: Information about the columns in the current database.
  4. KEY_COLUMN_USAGE: Information about the columns used as keys for tables.
  5. ROUTINES: Information about stored procedures and functions.
  6. PARAMETERS: Information about parameters used in stored procedures and functions.

Using the information_schema database, you can retrieve information about the database system and its structure, which can be useful for monitoring and managing your database. For example, you can use it to find information about the size of your tables or to check if a particular column exists in a table. You can also use it to generate reports or to automate tasks, such as generating SQL statements to alter tables or creating backups of the database.


How information_schema actually works

information_schema follows the SQL standard, and other databases such as PostgreSQL and SQL Server have the same thing, so the same queries mostly carry over. In MySQL it is not stored as files on disk. In MySQL 8.0 and later, most of its tables are views over the internal transactional data dictionary, which lives in InnoDB. In older versions they were temporary tables built on the fly by reading .frm files, so large servers queried them slowly.

  • Read-only: you cannot INSERT, UPDATE, DELETE or CREATE anything in it. Metadata only changes when you run DDL such as CREATE TABLE or ALTER TABLE.
  • Privilege-filtered: each user sees rows only for objects they have some privilege on. Two users running the same query can get different results.
  • Server-wide: tables like TABLES and COLUMNS cover every database you can access, not only the current one. Filter with TABLE_SCHEMA to limit the results.
  • Queryable with SQL: unlike SHOW TABLES or SHOW COLUMNS, you can join, filter, aggregate and build strings from the results.

Corrections to the description above

The overview above is broadly right, but a few details are misleading:

  • TABLES and COLUMNS describe tables and columns in all databases the current user can access, not just the current database. To limit results, add WHERE TABLE_SCHEMA = 'yourdb' or WHERE TABLE_SCHEMA = DATABASE().
  • information_schema cannot create backups. It can help you generate statements or lists of tables, but the backups themselves need tools such as mysqldump, the dump utilities in MySQL Shell, or physical backup tools.
  • Some values are estimates, not exact figures. For InnoDB, TABLE_ROWS is an estimate, and in MySQL 8.0 size and row statistics are cached (see the stale statistics section below).

Other useful information_schema tables

The list above names six tables. These are the others you are most likely to use:

TableWhat it tells you
STATISTICSIndexes: index name, columns, order within the index, uniqueness, cardinality
TABLE_CONSTRAINTSPrimary key, unique, foreign key and check constraints for each table
REFERENTIAL_CONSTRAINTSForeign key rules such as ON DELETE and ON UPDATE actions
VIEWSView definitions and their security settings
TRIGGERSTrigger timing, event and body
EVENTSScheduled events from the event scheduler
USER_PRIVILEGES, SCHEMA_PRIVILEGES, TABLE_PRIVILEGESGranted privileges at global, database and table level
CHARACTER_SETS, COLLATIONSCharacter sets and collations the server supports
INNODB_TRX, INNODB_TABLES and other INNODB_*InnoDB internals such as running transactions and tablespace metadata

Note: information_schema.PROCESSLIST is deprecated in recent MySQL 8.0 releases. Use performance_schema.processlist or SHOW PROCESSLIST instead.

Practical queries

Each query below uses aliases. In MySQL 8.0, columns selected from information_schema come back with uppercase names (TABLE_NAME) however you type them, so aliases keep the output, and any application code that reads it, predictable.

Size of each database in MB:

SELECT table_schema AS db_name,
       ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS size_mb
FROM information_schema.TABLES
GROUP BY table_schema
ORDER BY size_mb DESC;Code language: PHP (php)

The 10 largest tables in one database:

SELECT table_name AS tbl,
       engine,
       table_rows AS approx_rows,
       ROUND(data_length / 1024 / 1024, 2)  AS data_mb,
       ROUND(index_length / 1024 / 1024, 2) AS index_mb
FROM information_schema.TABLES
WHERE table_schema = 'shop'
  AND table_type = 'BASE TABLE'
ORDER BY data_length + index_length DESC
LIMIT 10;Code language: PHP (php)

Check whether a column exists before a migration adds it. This returns 1 if the column exists and 0 if it does not, which is handy in shell scripts:

SELECT COUNT(*) AS col_exists
FROM information_schema.COLUMNS
WHERE table_schema = 'shop'
  AND table_name   = 'orders'
  AND column_name  = 'status';Code language: PHP (php)

Find tables without a primary key. Missing primary keys hurt InnoDB performance and replication, and some managed and clustered MySQL services require one:

SELECT t.table_schema AS db_name, t.table_name AS tbl
FROM information_schema.TABLES t
LEFT JOIN information_schema.TABLE_CONSTRAINTS c
       ON c.table_schema = t.table_schema
      AND c.table_name   = t.table_name
      AND c.constraint_type = 'PRIMARY KEY'
WHERE t.table_type = 'BASE TABLE'
  AND c.constraint_name IS NULL
  AND t.table_schema NOT IN ('mysql','sys','information_schema','performance_schema');Code language: PHP (php)

List every foreign key that references a table. Run this before you drop or rename the table:

SELECT table_name AS child_table,
       column_name AS child_column,
       constraint_name AS fk_name,
       referenced_column_name AS parent_column
FROM information_schema.KEY_COLUMN_USAGE
WHERE referenced_table_schema = 'shop'
  AND referenced_table_name   = 'customers';Code language: PHP (php)

Generating SQL statements for automation

Because the metadata is just rows, you can use CONCAT() to build DDL and run the result as a script. The query below generates one ALTER TABLE per remaining MyISAM table to convert it to InnoDB:

SELECT CONCAT('ALTER TABLE `', table_schema, '`.`', table_name, '` ENGINE=InnoDB;') AS stmt
FROM information_schema.TABLES
WHERE engine = 'MyISAM'
  AND table_type = 'BASE TABLE'
  AND table_schema NOT IN ('mysql','sys','information_schema','performance_schema');Code language: PHP (php)
  1. Write the statements to a file. -N drops column headers and -B gives plain batch output: mysql -u admin -p -N -B -e "<query above>" > convert.sql
  2. Review convert.sql by hand and test it on a staging copy first.
  3. Run it in a maintenance window: mysql -u admin -p < convert.sql. Converting large tables rebuilds them and can take a long time.

The same pattern works for converting character sets, for example CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci, and for generating GRANT statements or ANALYZE TABLE runs.

Stale statistics and query performance

In MySQL 8.0, columns such as TABLE_ROWS, DATA_LENGTH, INDEX_LENGTH, AUTO_INCREMENT and UPDATE_TIME come from cached statistics. The information_schema_stats_expiry variable controls how long the cache lasts, and the default is 86400 seconds (24 hours). If a table has just grown, it can look unchanged.

-- Get fresh values for this session only
SET SESSION information_schema_stats_expiry = 0;

-- Or refresh statistics for a specific table
ANALYZE TABLE shop.orders;Code language: JavaScript (javascript)
  • Always filter by table_schema (and table_name where you can). Queries over the whole server are much slower when there are thousands of tables.
  • Monitoring agents that poll information_schema.TABLES often should use a long interval, because forcing fresh statistics has a real cost.
  • For exact row counts, run SELECT COUNT(*) on the table itself. TABLE_ROWS is only an estimate for InnoDB.

information_schema compared with the other system databases

DatabasePurposeWritable
information_schemaStandard metadata about objects, columns, constraints and privilegesNo
performance_schemaRuntime instrumentation: waits, statements, locks, connectionsOnly setup and configuration tables
sysReadable views and procedures built on performance_schema and information_schemaOnly its configuration table
mysqlInternal system tables: user accounts, time zones, replication metadataNot directly. Use CREATE USER, GRANT and similar statements

Common errors and fixes

  • Query returns no rows for a table you know exists: the user has no privileges on it. Grant at least SELECT (or another privilege) on that table, or run the query as an account that has access.
  • ERROR 1044 (42000): Access denied ... to database 'information_schema': you tried to change data or create objects in it. That is never allowed. Change metadata with DDL on the real objects instead.
  • Name matching fails on some servers: comparisons with table names depend on lower_case_table_names and the file system. Use the exact case the table was created with, or compare with LOWER().
  • Sizes or row counts look out of date: this is the statistics cache described above. Set information_schema_stats_expiry = 0 for the session or run ANALYZE TABLE.

Frequently asked questions

Can I delete or modify the information_schema database in MySQL?

No. It is a read-only system schema that the server provides. You cannot drop it, write to it or create objects in it, and it changes only when you run DDL on real objects.

Why does information_schema show different results for different users?

Rows are filtered by privilege, so each user sees only the databases, tables and routines they have some privilege on. Accounts with broad global privileges see everything.

Why is TABLE_ROWS in information_schema.TABLES inaccurate?

For InnoDB, TABLE_ROWS is an estimate based on sampled statistics, and in MySQL 8.0 it is also cached for the period set by information_schema_stats_expiry. Use SELECT COUNT(*) when you need an exact number.

What is the difference between information_schema and SHOW commands?

Both return metadata. SHOW TABLES, SHOW COLUMNS and SHOW INDEX are MySQL-specific shortcuts. information_schema is the SQL-standard interface that you can filter, join and aggregate with ordinary SELECT statements.

How do I find the size of a MySQL database using information_schema?

Add up data_length plus index_length from information_schema.TABLES, grouped by table_schema, then divide by 1024 twice to get megabytes. The first query in the practical queries section above does exactly this.

Related tutorials

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
I'm Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms. I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.

Related Posts

How to restore deleted ‘root’ user and password for MySQL

If the MySQL root account has been dropped or its password lost, restart the server with grant checks turned off, recreate the account with CREATE USER and…

Read More

MySql Tutorials: How to grant user access to Database?

To give a MySQL user access to one database, create the account with CREATE USER, then grant privileges on database_name.* with GRANT. The syntax in the example…

Read More

Oracle Tutorial: Install Oracle 19c EE

This guide installs Oracle Database 19c Enterprise Edition on Oracle Linux without the GUI. It uses the preinstall RPM, a software-only runInstaller run, and a DBCA response…

Read More

Step by Step Guide to Monitor PostGreSQL using Zabbix Agent

To monitor PostgreSQL with the classic Zabbix agent, you install the agent on the database host, create a read-only monitoring role, and deploy the user parameters and…

Read More

How to Configure Artifactrory with MySQL Database?

To run JFrog Artifactory 7 on MySQL instead of the default embedded Derby database, you create a dedicated database and user, put the MySQL Connector/J JAR in…

Read More

Python Tutorials: Database operations using python – mysql

This tutorial connects Python to MySQL with the official mysql-connector-python driver and runs the full set of CRUD operations: create a database and table, then insert, read,…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x