13

I want to add a column to a table, but I don't want it to fail if it has already been added to the table. How can I achieve this?

# Add column fails if it already exists 
ALTER TABLE `TableName` ADD `ColumnName` int(1) NOT NULL default '0';
1

1 Answer 1

18

Use the following in a stored procedure:

IF NOT EXISTS( SELECT NULL
            FROM INFORMATION_SCHEMA.COLUMNS
           WHERE table_name = 'tablename'
             AND table_schema = 'db_name'
             AND column_name = 'columnname')  THEN

  ALTER TABLE `TableName` ADD `ColumnName` int(1) NOT NULL default '0';

END IF;

Reference:

Sign up to request clarification or add additional context in comments.

3 Comments

Why the != comparison. I suspect there must be a good reason for it.
@SaadFarooq: Corrected the column check, but the syntax is otherwise correct -- COLUMN is optional if you check the documentation
I get a syntax error. Seems to choke after INFORMATION_SCHEMA.COLUMNS. Did the schema change in MySQL 5.6?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.