14

I've got a database with about 100 tables and I need to build a join query to get specific data from two of them. I know one but not the other. Basically I need something like:

select <tables> from <database> where exists table.column name;

How can I do this?

Joe Essey
  • 351
  • 1
  • 6
  • 11

8 Answers8

23

Using information_schema

This is the standards-compliant cross-RDBMS way to do it.

SELECT table_catalog, table_schema, table_name, column_name
FROM INFORMATION_SCHEMA.columns
WHERE column_name = '<your column name>';

You can see this documented

Evan Carroll
  • 65,432
  • 50
  • 254
  • 507
SqlSandwiches
  • 1,617
  • 1
  • 15
  • 20
5

For IBM DB2 you would use the following:

select tabschema,tabname from syscat.columns where colname = 'COLUMN_NAME'

Note that in DB2, column names will be in upper case unless they were defined inside of double quotes with something other than upper case. Then you have to supply the exact casing of the column name as well.

Chris Aldrich
  • 4,916
  • 5
  • 34
  • 55
3

The below query should give you what you're looking for:

use YourDatabase;
go

select
    object_schema_name(t.object_id) + '.' + t.name as table_name,
    c.name as column_name
from sys.tables t
inner join sys.columns c
on t.object_id = c.object_id
where c.name like '%ColumnSearchText%';

If you're looking for columns of an exact name, just replace the WHERE clause with:

where c.name = 'ColumnSearchText';
Thomas Stringer
  • 42,434
  • 9
  • 120
  • 155
0

in Teradata 15:

SELECT DATABASENAME||'.'||TABLENAME AS FULL_TABLENAME,
COUNT(1) AS NUMBER_OF_COLUMNS
FROM DBC.COLUMNSV
WHERE 1 = 1
AND COLUMNNAME LIKE '%<YOUR COLUMNNAME HERE>%'
GROUP BY 1
0

Oracle sql / plsql:

select table_name from all_tab_columns where column_name='yourcolumnname';
Tim Chaubet
  • 101
  • 2
0
SELECT * FROM _v_sys_columns WHERE COLUMN_NAME='$COLUMN_NAME'

Please pass the column name to this variable: $COLUMN_NAME

tinlyx
  • 3,810
  • 14
  • 50
  • 79
Yasim
  • 1
-3

//Select the Particular table:

SYNTAX:
       SELECT COLUMN_NAME FROM TABLE_NAME WHERE COLUMN_NAME='VALUE';
EXAMPLE:
       SELECT PERSON_NAME FROM PERSON WHERE PERSON_ID=1;
selvi
  • 1
-3

For SQL Server:

SELECT name 
FROM sysobjects 
WHERE id IN 
( 
    SELECT id 
    FROM syscolumns 
    WHERE name = 'EXACT_COLUMN_NAME_TO_SEARCH'
)
Paul White
  • 94,921
  • 30
  • 437
  • 687