34
IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS
  WHERE TABLE_NAME = 'email_subscription' AND COLUMN_NAME = 'subscribe_all')
  THEN 
  ALTER TABLE email_subscription
  ADD COLUMN subscribe_all TINYINT(1) DEFAULT 1,
  ADD COLUMN subscribe_category varchar(512) DEFAULT NULL;

I had a look at huge amount of examples. but this query doesn't work, I got error of:

ERROR 1064 (42000): 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 * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME =' at line 1

4
  • 2
    Are you doing this inside a stored procedure? The IF ELSE isn't valid outside a procedure or function. Commented Jan 17, 2013 at 15:04
  • 1
    Hey, I see ! I do have a proceedure covered on top and didn;t work as well. Commented Jan 17, 2013 at 15:08
  • Does this answer your question? add column to mysql table if it does not exist Commented Apr 13, 2020 at 14:29
  • possible duplicate stackoverflow.com/questions/972922/… Commented Oct 7, 2021 at 21:04

7 Answers 7

33

If your host doesn't give you permission to create or run procedures, I think I found another way to do this using PREPARE/EXECUTE and querying the schema:

SET @s = (SELECT IF(
    (SELECT COUNT(*)
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE table_name = 'table_name'
        AND table_schema = DATABASE()
        AND column_name = 'col_name'
    ) > 0,
    "SELECT 1",
    "ALTER TABLE table_name ADD col_name VARCHAR(100)"
));

PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Sign up to request clarification or add additional context in comments.

1 Comment

Excellent for use in ad hoc scripts.
24

you can create a procedure for the query,

DELIMITER $$
CREATE PROCEDURE Alter_Table()
BEGIN
    DECLARE _count INT;
    SET _count = (  SELECT COUNT(*) 
                    FROM INFORMATION_SCHEMA.COLUMNS
                    WHERE   TABLE_NAME = 'email_subscription' AND 
                            COLUMN_NAME = 'subscribe_all');
    IF _count = 0 THEN
        ALTER TABLE email_subscription
            ADD COLUMN subscribe_all TINYINT(1) DEFAULT 1,
            ADD COLUMN subscribe_category varchar(512) DEFAULT NULL;
    END IF;
END $$
DELIMITER ;

5 Comments

There is logical error in script, if table not exists the Count = 0 also. You need first check for table existence, then for column.
@HamletHakobyan i'm assuming that the table provided existed.
I got 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 '@count INT;
Hey bralliant, it now passes. do I have to call this function somewhere to make it running?
Actually, it's working, I just run call Alter_Table() and it works ! thanks !
4

You are using MS SQL Server syntax in MySQL.

1 Comment

Hah! I knew something was off but I couldn't put my finger on it :)
3

There is no equivalent syntax to achieve this in a single MySQL statement.

To get something simlilar, you can either

1) attempt to add the column with an ALTER TABLE, and let MySQL raise an error if a column of that name already exists in the table, or

2) query the information_schema.columns view to check if a column of that name exists in the table.

Note that you really do need to check for the table_schema, as well as the table_name:

SELECT column_name
  FROM information_schema.columns 
 WHERE table_schema = 'foo'
   AND table_name   = 'email_subscription'
   AND column_name  = 'subscribe_all'

and based on that, decide whether to run the ALTER TABLE

Comments

2

Also add condition for database name to check column existance.

Try this:

DELIMITER $$
CREATE PROCEDURE sp_AlterTable()
BEGIN
    IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS 
                   WHERE TABLE_SCHEMA = 'dbName' AND 
                         TABLE_NAME = 'email_subscription' AND 
                         COLUMN_NAME = 'subscribe_all') THEN 
       ALTER TABLE email_subscription
          ADD COLUMN subscribe_all TINYINT(1) DEFAULT 1,
          ADD COLUMN subscribe_category VARCHAR(512) DEFAULT NULL;
    END IF; 
END $$
DELIMITER ;

Comments

0
SET @s = (SELECT IF(
    (SELECT COUNT(column_name)
          FROM INFORMATION_SCHEMA.COLUMNS
          WHERE table_name = 'oc_bitcoin_wallets_receive'
          AND table_schema = 'k_opencart2'
          AND column_name = 'test3'
    ) > 0,
    "SELECT 1",
    "ALTER TABLE `oc_bitcoin_wallets_receive` ADD COLUMN `test3` INT NOT NULL AFTER `test2`;"
));
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Values for edit: oc_bitcoin_wallets_receive - table name, k_opencart2 - database name, test3 - name of new column, oc_bitcoin_wallets_receive - second location table test3 - second location column, test2 - name of column before new column.

Comments

0

I am late to the party but a universal solution that works for all mysql servers is;

$query = "SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'yourtablename' AND table_schema = DATABASE() AND column_name = 'yourcolumnname'"; $result=mysqli_query($link, $query); if(mysqli_num_rows($result) == 0){ $query2 = ("ALTER TABLE yourtablename ADD yourcolumname VARCHAR( 100 ) NOT NULL"); $create = mysqli_query($link, $query2); }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.