Home >Database >Mysql Tutorial >How to Safely Add a MySQL Column Only if It Doesn't Exist?
Issue:
You want to add a column to an existing MySQL table without overwriting existing data, but only if the column does not already exist.
Solution:
Here's a comprehensive method to safely add a column to a table using a stored procedure:
DELIMITER $$ DROP PROCEDURE IF EXISTS add_column_if_not_exists $$ CREATE PROCEDURE add_column_if_not_exists() BEGIN -- Add a column if it does not exist IF NOT EXISTS( (SELECT * FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND COLUMN_NAME='my_new_column' AND TABLE_NAME='my_table_name') ) THEN ALTER TABLE my_table_name ADD my_new_column varchar(255) NOT NULL DEFAULT ''; END IF; END $$ CALL add_column_if_not_exists() $$ DELIMITER ;
This solution addresses the following factors:
The above is the detailed content of How to Safely Add a MySQL Column Only if It Doesn't Exist?. For more information, please follow other related articles on the PHP Chinese website!