// SQL snippet

Rename a column if it exists

Renames fail loudly when the column is already renamed, which breaks idempotent migrations. Guard the rename with a metadata check per engine.

Main statement
SQL Server
Também cobre
PostgreSQL MySQL SQLite

The task

One environment already has the new column name and another does not, so the migration has to detect which state it is in before it acts.

The snippet

Written for SQL Server. Versions for PostgreSQL, MySQL and SQLite are under Variations.

SQL Server
IF COL_LENGTH('dbo.Users', 'username') IS NOT NULL
    EXEC sp_rename 'dbo.Users.username', 'user_name', 'COLUMN';

Como funciona

COL_LENGTH returns NULL for a missing column, so the IF makes the block a no-op once the column has been renamed; SQL Server has no IF EXISTS clause for renames. sp_rename takes the old name qualified and the new name bare; qualifying the new name too would make the brackets part of the column name. sp_rename does not update views or procedures that mention the old name, so search sys.sql_modules for it afterwards.

Variations

PostgreSQL

PostgreSQL
-- RENAME COLUMN has no IF EXISTS; guard it with a DO block
DO $$
BEGIN
  IF EXISTS (SELECT 1 FROM information_schema.columns
             WHERE table_schema = 'public' AND table_name = 'users'
               AND column_name = 'username') THEN
    ALTER TABLE public.users RENAME COLUMN username TO user_name;
  END IF;
END $$;

MySQL

MySQL
-- RENAME COLUMN needs MySQL 8.0+; no IF EXISTS, so build
-- the statement conditionally
SET @sql := IF(EXISTS (
    SELECT 1 FROM information_schema.columns
    WHERE table_schema = DATABASE()
      AND table_name = 'users' AND column_name = 'username'),
  'ALTER TABLE users RENAME COLUMN username TO user_name',
  'DO 0');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SQLite

SQLite
ALTER TABLE users RENAME COLUMN username TO user_name;
-- SQLite 3.25+; also rewrites references in indexes,
-- triggers and views. Check pragma_table_info first.

Questions that come up

What breaks when a column is renamed?

Anything that stores the old name as text. Views on MySQL and SQL Server keep the old name and fail at the next SELECT; PostgreSQL views follow the rename because they reference columns by number. Stored procedures and functions, ORM mappings, reports and SQL in application code all break on every engine. Search the codebase and the module definitions for the old name before the rename, not after.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.