How can I test if a column exists in a table using an SQL statement

南楼画角 提交于 2019-11-27 20:21:44

Try this :

SELECT column_name 
FROM information_schema.columns 
WHERE table_name='your_table' and column_name='your_column';

Accepted answer is correct, but is missing the schema and nicer output (True/False):

SELECT EXISTS (SELECT 1 
FROM information_schema.columns 
WHERE table_schema='my_schema' AND table_name='my_table' AND column_name='my_column');

This is simpler (and SQLi-safe) with PostgreSQL's object identifier types:

SELECT TRUE
FROM   pg_attribute 
WHERE  attrelid = 'myTable'::regclass  -- cast to a registered class (table)
AND    attname = 'myColumn'
AND    NOT attisdropped  -- exclude dropped (dead) columns
-- AND attnum > 0        -- exclude system columns (you may or may not want this)

Read about the significance of the columns in the manual.

If you are building dynamic SQL and your column name is supplied as parameter, you might want to use quote_ident() to avoid SQL injection:

...
AND    attname = quote_ident('myColumn');

Works for tables outside the search_path, too:

...
WHERE  attrelid = 'mySchema.myTable'::regclass
...
SELECT attname 
FROM pg_attribute 
WHERE attrelid = (SELECT oid FROM pg_class WHERE relname = 'YOURTABLENAME') 
AND attname = 'YOURCOLUMNNAME';

Of course, replace YOURTABLENAME and YOURCOLUMNNAME with the proper values. If a row is returned, a column with that name exists, otherwise it does not.

Unlike Oracle, PostgreSQL supports the ANSI standard INFORMATION_SCHEMA views.

The corresponding standard view to Oracle's user_tab_columns is information_schema.columns

http://www.postgresql.org/docs/current/static/infoschema-columns.html

Here is a similar variant of Erwin Brandstetter answer. Here we check schema too in case we have similar tables in different schema.

SELECT TRUE FROM pg_attribute 
WHERE attrelid = (
    SELECT c.oid
    FROM pg_class c
    JOIN pg_namespace n ON n.oid = c.relnamespace
    WHERE 
        n.nspname = CURRENT_SCHEMA() 
        AND c.relname = 'YOURTABLENAME'
    )
AND attname = 'YOURCOLUMNNAME'
AND NOT attisdropped
AND attnum > 0
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!