Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Benjaminhu/3359851765dacda8653ad426af0cb850 to your computer and use it in GitHub Desktop.
Save Benjaminhu/3359851765dacda8653ad426af0cb850 to your computer and use it in GitHub Desktop.
MySQL ALTER TABLE IF NOT EXISTS - I think so best alternative
-- <TABLE NAME> replace to table name
-- <COLUMN> replace to column name
SELECT COUNT(*) INTO @exist FROM information_schema.columns
WHERE table_schema = DATABASE() AND table_name = '<TABLE NAME>' AND column_name = '<COLUMN>' LIMIT 1;
SET @query = IF (@exist <= 0,
"ALTER TABLE <TABLE NAME> ADD COLUMN <COLUMN> MEDIUMTEXT NULL",
"SELECT 'COLUMN EXISTS: <TABLE NAME>.<COLUMN>' AS column_exists_info"
);
PREPARE stmt FROM @query;
EXECUTE stmt;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment