// dialect comparison

Rename a column

A metadata-only rename, if your engine has the standard syntax.

Filed under Tables & schema

The verdict

Use RENAME COLUMN wherever it exists. On SQL Server, and for function bodies in PostgreSQL, views in MySQL, or views and PL/SQL in Oracle, search the dependent code for the old name before you rename.

Where they differ

ALTER TABLE … RENAME COLUMN works in every engine here except SQL Server, which uses the sp_rename procedure. sp_rename does not update views, procedures or functions that mention the old name, so renames there need a search through the dependent code.

How each engine writes it

SQL Server

EXEC sp_rename 'customers.email', 'contact_email', 'COLUMN';

No ALTER … RENAME COLUMN. sp_rename warns that changing an object name can break scripts and stored procedures, and leaves them unchanged; they fail when next run.

PostgreSQL

ALTER TABLE customers RENAME COLUMN email TO contact_email;

Metadata-only. Views, indexes and constraints follow automatically because they store column references, not names. Function bodies are stored as text and break.

MySQL

ALTER TABLE customers RENAME COLUMN email TO contact_email;

8.0+. MySQL 5.7 and MariaDB before 10.5.2 need CHANGE COLUMN email contact_email VARCHAR(320), restating the full definition. Views that use the old name are not updated and fail with error 1356 until you recreate them.

SQLite

ALTER TABLE customers RENAME COLUMN email TO contact_email;

3.25+. SQLite also rewrites references in the table's indexes, triggers and views.

Oracle

ALTER TABLE customers RENAME COLUMN email TO contact_email;

Metadata change. Indexes and constraints follow; views and PL/SQL that use the old name become invalid and fail to recompile.

Questions that come up

Why is sp_rename on SQL Server frowned upon?

It changes the name and nothing else: views, procedures, functions and application SQL that mention the old name keep doing so and fail at run time. Find the dependents first with sys.sql_expression_dependencies or a text search of sys.sql_modules.

Does renaming break indexes or constraints?

No. Indexes and constraints reference the column internally, so they follow the rename on all five engines. What breaks is code that stores the name as text: SQL Server modules, PostgreSQL function bodies, MySQL views, Oracle views and PL/SQL, and application queries.

What about a view that selects the column?

PostgreSQL and SQLite update the view, and PostgreSQL even keeps the view's output column name. On SQL Server, MySQL and Oracle, recreate the view after the rename (on SQL Server, sp_refreshview is not enough when the name changed).

Keep reading

// write it once, run it anywhere

Switch engines without relearning SQL

SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.