Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save grocky/018908bd460550b55bcf7fec83fc76a4 to your computer and use it in GitHub Desktop.
Save grocky/018908bd460550b55bcf7fec83fc76a4 to your computer and use it in GitHub Desktop.
Idempotent SQL Alter Table Statements
-- Idempotently add the tasks.id column
SET @table_name = 'tasks';
SET @column_name = 'id';
SET @preparedStatement = (SELECT IF(
(
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = @table_name
AND column_name = @column_name
AND data_type = 'BIGINT'
) > 0,
"SELECT 1",
CONCAT("ALTER TABLE ", @table_name, " ADD COLUMN ", @column_name, " BIGINT(20) COMMENT 'primary key for tasks';")
));
PREPARE alterIfNotExists FROM @preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;
-- Idempotently remove the tasks.id column
SET @table_name = 'tasks';
SET @column_name = 'id';
SET @preparedStatement = (SELECT IF(
(
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = @table_name
AND column_name = @column_name
) > 0,
CONCAT("ALTER TABLE ", @table_name, " DROP COLUMN ", @column_name),
"SELECT 1"
));
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