Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: How to add a column if it doesn't already exist?

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';
like image 237
Andrew Avatar asked Jul 13 '10 22:07

Andrew


People also ask

How do I add a column to an existing MySQL table?

The syntax to add a column in a table in MySQL (using the ALTER TABLE statement) is: ALTER TABLE table_name ADD new_column_name column_definition [ FIRST | AFTER column_name ]; table_name. The name of the table to modify.

How do I add a column to an already created table?

The basic syntax of an ALTER TABLE command to add a New Column in an existing table is as follows. ALTER TABLE table_name ADD column_name datatype; The basic syntax of an ALTER TABLE command to DROP COLUMN in an existing table is as follows.


1 Answers

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:

  • The INFORMATION_SCHEMA COLUMNS Table
like image 157
OMG Ponies Avatar answered Oct 05 '22 06:10

OMG Ponies