Skip to content

Instantly share code, notes, and snippets.

@moeryomenko
Created December 16, 2021 15:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moeryomenko/1a5e82cec21c92e07959969b0166b0fb to your computer and use it in GitHub Desktop.
Save moeryomenko/1a5e82cec21c92e07959969b0166b0fb to your computer and use it in GitHub Desktop.
mysql5 if not exists emulation
--- if not exists index
SET @dbname = DATABASE();
SET @tablename = "TABLENAME";
SET @indexname = "INDEXNAME";
SET @preparedStatement =
(SELECT IF (EXISTS
(SELECT COUNT(*)
FROM information_schema.statistics
WHERE (table_schema = @dbname)
AND (table_name = @tablename)
AND (index_name = @indexname) ) > 0,
"SELECT 1",
CONCAT("ALTER TABLE ", @tablename, " ADD CONSTRAINT ", @indexname, " UNIQUE KEY(<keys...>);")));
PREPARE alterIfNotExists
FROM @preparedStatment;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;
--- if not exists column
SET @dbname = DATABASE();
SET @tablename = "TABLENAME";
SET @columnname = "COLUMNNAME";
SET @preparedStatement =
(SELECT IF(
(SELECT COUNT(*)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE (table_name = @tablename)
AND (table_schema = @dbname)
AND (column_name = @columnname) ) > 0, "SELECT 1", CONCAT("ALTER TABLE ", @tablename, " ADD ", @columnname, " text NOT NULL;")));
PREPARE alterIfNotExists
FROM @preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment