SQL Server with Mike250

Find Column in Any Table with SQL (MySQL, MSSQL, PostgreSQL)

Ever needed to find out if or where a specific column exists within your database tables? Whether you are doing a schema audit, reverse engineering an unknown dataset, or trying to locate a particular field for reporting, it is surprisingly common to ask: Which tables contain this column?

Fortunately, MySQL, MSSQL, and PostgreSQL all allow you to query their metadata to answer this question. The queries are remarkably similar, though there are small differences in naming conventions across systems.

MySQL Example

In MySQL, the query looks like this:

SELECT COLUMN_NAME, TABLE_NAME  
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME IN ('club', 'ClubID')
AND TABLE_SCHEMA = 'mydatabase';
The key filter here is TABLE_SCHEMA, which refers to the database name in MySQL. This limits the results to a specific database.

MSSQL Example

For Microsoft SQL Server, the query is nearly identical except for one key difference: TABLE_CATALOG is used instead of TABLE_SCHEMA.

SELECT COLUMN_NAME, TABLE_NAME 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE COLUMN_NAME IN ('club', 'ClubID')
AND TABLE_CATALOG = 'mydatabase';

You can also replace the IN clause with a LIKE condition if you are not sure of the exact column name:

WHERE COLUMN_NAME LIKE '%club%'

PostgreSQL Example

In PostgreSQL, the metadata is slightly more granular. Use this query to find a column in a specific schema:

SELECT column_name, table_name 
FROM information_schema.columns 
WHERE column_name IN ('club', 'ClubID')
AND table_schema = 'public';

As with the others, you can use LIKE for partial matches.

Why You Might Need This

There are several reasons you might need to locate a column across multiple tables:

  • Data Audits: If you are assessing data quality or completeness, you may need to verify where certain fields exist.
  • Legacy Systems: When working with an unfamiliar or undocumented schema, this approach helps you reverse engineer relationships.
  • Report Development: BI developers often need to know which tables to join or where a particular measure or dimension lives.
  • Refactoring: When consolidating or renaming fields, it is critical to know everywhere a column is used before making changes.

This type of metadata query is a quick, efficient tool that can save you hours of manual inspection. If you are using an older version of MySQL that does not support INFORMATION_SCHEMA, you will need to export the table definitions and search them manually.

Leave a reply