PostgreSQL: Determine if a column exists or not.

Here’s a quick query you can run to determine whether or not a particular column in a table exists or not:

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.

6 responses to “PostgreSQL: Determine if a column exists or not.”

  1. Michael says:

    Thanks for this 🙂

  2. Another says:

    Another thank you for taking the time to post this.

  3. Celessstino says:

    Useful, Thank you.

  4. David Mountain says:

    This creates a function to check if a column exists

    — check if a column exists
    CREATE OR REPLACE FUNCTION column_exists(colname text, tablename text)
    RETURNS boolean AS
    $BODY$
    DECLARE

    q text;
    onerow record;

    BEGIN
    q = ‘SELECT attname FROM pg_attribute WHERE attrelid = ( SELECT oid FROM pg_class WHERE relname = ”’||tablename||”’) AND attname = ”’||colname||”’ ‘;
    FOR onerow IN EXECUTE q
    LOOP
    RETURN true;
    END LOOP;
    RETURN false;
    END;
    $BODY$
    LANGUAGE ‘plpgsql’ VOLATILE

  5. Hoang_vn says:

    Thanks for this

  6. HungryTom says:

    Wicked! Cheers