How to find a table having a specific column in postgresql

SqlDatabasePostgresqlPostgresql 9.1

Sql Problem Overview


I'm using PostgreSQL 9.1. I have the column name of a table. Is it possible to find the table(s) that has/have this column? If so, how?

Sql Solutions


Solution 1 - Sql

You can also do

 select table_name from information_schema.columns where column_name = 'your_column_name'

Solution 2 - Sql

you can query system catalogs:

select c.relname
from pg_class as c
    inner join pg_attribute as a on a.attrelid = c.oid
where a.attname = <column name> and c.relkind = 'r'

sql fiddle demo

Solution 3 - Sql

I've used the query of @Roman Pekar as a base and added schema name (relevant in my case)

select n.nspname as schema ,c.relname
    from pg_class as c
    inner join pg_attribute as a on a.attrelid = c.oid
    inner join pg_namespace as n on c.relnamespace = n.oid
where a.attname = 'id_number' and c.relkind = 'r'

sql fiddle demo

Solution 4 - Sql

Simply:

$ psql mydatabase -c '\d *' | grep -B10 'mycolname'

Enlarge -B offset to get table name, if need

Solution 5 - Sql

Wildcard Support Find the table schema and table name that contains the string you want to find.

select t.table_schema,
       t.table_name
from information_schema.tables t
inner join information_schema.columns c on c.table_name = t.table_name
                                and c.table_schema = t.table_schema
where c.column_name like '%STRING%'
      and t.table_schema not in ('information_schema', 'pg_catalog')
      and t.table_type = 'BASE TABLE'
order by t.table_schema;

Solution 6 - Sql

select t.table_schema,
       t.table_name
from information_schema.tables t
inner join information_schema.columns c on c.table_name = t.table_name 
                                and c.table_schema = t.table_schema
where c.column_name = 'name_colum'
      and t.table_schema not in ('information_schema', 'pg_catalog')
      and t.table_type = 'BASE TABLE'
order by t.table_schema;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionQuestionEverythingView Question on Stackoverflow
Solution 1 - SqlRavi ShekharView Answer on Stackoverflow
Solution 2 - SqlRoman PekarView Answer on Stackoverflow
Solution 3 - SqljutkyView Answer on Stackoverflow
Solution 4 - SqlDmitryView Answer on Stackoverflow
Solution 5 - SqljjjView Answer on Stackoverflow
Solution 6 - SqlromuloMendesView Answer on Stackoverflow