Recipe · SQL recipes

Renaming columns and tables with ALTER TABLE

Rename using your engine's syntax and update the queries that use the old name. The data stays, but some dependencies may need changes.

Before continuing: This entry is part of the ALTER TABLE guide. If you are new to the topic, start with ALTER TABLE.

Query

Temporary demo table
CREATE TABLE customers_demo (
  id INTEGER PRIMARY KEY,
  name TEXT NOT NULL,
  phone TEXT
);

INSERT INTO customers_demo (id, name, phone)
VALUES (1, 'Amy', '+44 20 0000 0000');

ALTER TABLE customers_demo
RENAME COLUMN phone TO moving;

ALTER TABLE customers_demo
RENAME TO contacts_demo;

SELECT id, name, moving
FROM contacts_demo;

The row itself does not change. Only the identifiers used to find the table and the column change.

How it works

PostgreSQL and SQLite use these forms. Recent versions of MySQL support RENAME COLUMN and also keep older variants such as CHANGE. SQL Server uses the stored procedure sys.sp_rename to rename columns and other objects, not this form of ALTER TABLE.

Cases that change the result

  1. Search for the old name in code, views, procedures, reports and documentation.
  2. Check dependencies on a copy of the database.
  3. Update the consumers that can handle both names first, or coordinate a joint release.
  4. Run the change during a controlled maintenance window.
  5. Test reads, writes and permissions with the new name.

Avoid this confusion

Assuming everything will update itself

SQLite updates internal references when the change can be resolved unambiguously, but an ambiguous view or trigger can cause the operation to fail. SQL Server warns that renaming objects does not automatically update all references.

Do not use a rename to change what the data means without also reviewing types, constraints and documentation. A new name does not fix a column that was modelled wrongly.

Key differences between engines

PostgreSQL, MySQL and SQLite document ways to rename tables and columns. SQL Server uses sys.sp_rename for columns and objects. In SQLite, a column rename is carried through to indexes, triggers and views when it does not create a semantic ambiguity; for tables, the way foreign keys were handled historically depends on old versions and settings, so use a recent version and review the schema.