In MySQL, you can retrieve all column names for all tables by querying the information_schema database. information_schema is a special MySQL database that stores metadata about the database, such as table structures and column information.
Here is a specific SQL query example that returns the column names for all tables in a specified database:
sqlSELECT TABLE_NAME, COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = 'your_database_name';
In this query:
TABLE_NAMErepresents the name of the table where the column resides.COLUMN_NAMEis the name of the column.TABLE_SCHEMAspecifies the database name where the column resides; replace'your_database_name'with your target database name.
This query returns all column names and their respective table names for the specified database.
Suppose we have a database named school containing two tables, students and teachers. The students table has three columns: id, name, and grade, while the teachers table has three columns: id, name, and subject. Executing this query will yield the following results:
| TABLE_NAME | COLUMN_NAME |
|---|---|
| students | id |
| students | name |
| students | grade |
| teachers | id |
| teachers | name |
| teachers | subject |
This allows you to clearly see which columns exist in each table and their names. This is very useful for database management, maintenance, or data migration.