'MySQL add column if not exist error

How do I add a column if not exist in MySQL?

I have tried this, but it doesn't work anymore in the latest MySQL:

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;

The error:

[Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF NOT EXISTS (
    SELECT
        NULL
    FROM
        INFORMATION_SCHEMA.COLUMNS
    WHERE
    ' at line 1


Solution 1:[1]

Sole reason you get that error cause you are trying to run it individually whereas that IF block has to be executed inside a procedure block like below

create procedure usp_addcol
as
begin
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;
end;

Now you can just call the procedure.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rahul