MySQL ALTER TABLE ADD COLUMN IF NOT EXISTS

I had been looking for a one-line solution for adding columns to tables when they do not already exist. For the longest time I settled on using a temporary stored procedure, but this still required at least four lines to execute using the 3rd party system I am sometimes constrained within…

DROP PROCEDURE IF EXISTS `AddColumnIfNotExists`;
DELIMITER $$ CREATE PROCEDURE `AddColumnIfNotExists`() BEGIN DECLARE CONTINUE HANDLER FOR SQLEXCEPTION BEGIN END; ALTER TABLE `t1` ADD `c1` TEXT; END $$ DELIMITER ;
CALL `AddColumnIfNotExists`();
DROP PROCEDURE `AddColumnIfNotExists`;

While that works fine, I was still displeased with having to use a stored procedure to achieve the desirable result. So, I eventually came up with this beautiful one-liner…

ALTER TABLE `t1` ADD COLUMN IF NOT EXISTS `c1` TEXT

No more relying on that store procedure!

Hope it helps you out along the way.

Leave a Reply

Your email address will not be published. Required fields are marked *