Search code examples
mysqlsqlalter-table

ADD column if none exists in MySQL


I figure this is very easy, but I am trying to run this command only if those columns already don't exist:

ALTER TABLE `surveytable` ADD IF NOT EXISTS  Survey_Name_Qualtrics VARCHAR(20);
ALTER TABLE `surveytable` ADD IF NOT EXISTS Survey_URL_Qualtrics VARCHAR(600);

Solution

  •     CREATE PROCEDURE addcol() BEGIN
          IF NOT EXISTS(
            SELECT * FROM information_schema.COLUMNS
            WHERE COLUMN_NAME='new_column' AND TABLE_NAME='the_table' AND TABLE_SCHEMA='the_schema'
            )
        THEN
            ALTER TABLE `the_schema`.`the_table`
            ADD COLUMN `new_column` bigint(20) unsigned NOT NULL default 1;
    
           END IF;
        END;
    
    
         delimiter ';'
    
         CALL addcol();
    
    DROP PROCEDURE addcol;
    

    This is the code that i use, i dont think you can use if not exists on a ALTER column.

    An alternative you can watch for the error you get if you try to insert a column that already exists, i think its 1062. And handle the error.

    Of course the better way is to not get the error in the first place.