how to drop a column if exists in mysql?

CloudSeph picture CloudSeph · Sep 28, 2016 · Viewed 23.9k times · Source
ALTER TABLE user DROP COLUMN registered_date

We can drop a column using the above command. But how can i drop it only if the column registered_date exist?

Answer

Jibin Balachandran picture Jibin Balachandran · Sep 28, 2016
IF EXISTS(SELECT * 
          FROM information_schema.COLUMNS 
          WHERE 
          TABLE_SCHEMA = 'db_name' 
          AND TABLE_NAME = 'table_name' 
          AND COLUMN_NAME = 'column_name')
BEGIN
 ALTER TABLE table_name DROP COLUMN column_name
END

OR

IF (SELECT COUNT(*) 
          FROM information_schema.COLUMNS 
          WHERE 
          TABLE_SCHEMA = 'db_name' 
          AND TABLE_NAME = 'table_name' 
          AND COLUMN_NAME = 'column_name'>0)
BEGIN
 ALTER TABLE table_name DROP COLUMN column_name
END