// SQL snippet

Find every table that has a given column

Rename a column and half the schema breaks, unless you first find everywhere it appears. This query searches the metadata for every table that has a column with a given name.

Main statement
MySQL
次もカバーします
SQL Server PostgreSQL SQLite

The task

A shared column shows up in far more tables than anyone remembers, and work such as a rename or encryption pass needs the complete hit list up front.

The snippet

Written for MySQL. Versions for SQL Server, PostgreSQL and SQLite are under Variations.

MySQL
SELECT table_schema, table_name, column_name, data_type
FROM information_schema.columns
WHERE column_name = 'email'
  AND table_schema = 'mydb'
ORDER BY table_name;

仕組み

information_schema.columns is one row per column of every table, so a filter on column_name finds every table storing that field. Add table_schema to scope the search; without it you also scan system schemas. Column names are case-insensitive in MySQL, so 'email' also matches Email. On PostgreSQL the match is exact against the stored name, which is lowercase unless the column was created with a quoted mixed-case identifier.

Variations

PostgreSQL

PostgreSQL
SELECT table_schema, table_name, column_name, data_type
FROM information_schema.columns
WHERE column_name = 'email'
  AND table_schema NOT IN ('pg_catalog', 'information_schema')
ORDER BY table_schema, table_name;

SQL Server

SQL Server
SELECT SCHEMA_NAME(t.schema_id) AS schema_name,
       t.name AS table_name,
       c.name AS column_name
FROM sys.columns c
JOIN sys.tables t ON t.object_id = c.object_id
WHERE c.name = 'email'
ORDER BY schema_name, table_name;
-- join sys.objects instead to include views and functions

SQLite

SQLite
SELECT m.name AS table_name, ti.name AS column_name
FROM sqlite_master m
JOIN pragma_table_info(m.name) ti ON true
WHERE m.type = 'table' AND m.name NOT LIKE 'sqlite_%'
  AND ti.name = 'email'
ORDER BY m.name;

Questions that come up

Does this also search views?

The information_schema version does: views appear in information_schema.columns alongside tables. Join information_schema.tables and filter table_type = 'BASE TABLE' to drop them. The SQL Server and SQLite variants above list tables only; use sys.objects, or m.type IN ('table', 'view'), to include views.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.