Sub topic 7
Renaming columns and tables
This chapter assumes you can write CREATE TABLE, you know what primary and foreign keys are, and you have a test database (PostgreSQL, MySQL, SQL Server or SQLite). You should also know the basic ALTER TABLE shape from the earlier chapters: ALTER TABLE table_name action.
A rename changes only a name. The data does not move and no values are rewritten. This makes renames cheap for the database, but they can be expensive for everything else that uses the old name.
Renaming a column
The standard form is RENAME COLUMN old TO new. PostgreSQL, MySQL 8.0, Oracle and SQLite 3.25 and later all accept it.
ALTER TABLE customers RENAME COLUMN name TO full_name;SQL Server has no RENAME COLUMN. It uses the stored procedure sp_rename. The first argument is the current name qualified with the table, and the third argument says what kind of object you are renaming.
EXEC sp_rename 'customers.name', 'full_name', 'COLUMN';Give only the new column name as the second argument. Do not write customers.full_name, or you will end up with a column literally named customers.full_name.
MySQL 5.7 and earlier have no RENAME COLUMN. They use CHANGE, which makes you restate the whole column definition:
ALTER TABLE customers CHANGE COLUMN name full_name VARCHAR(100) NOT NULL;If you leave out NOT NULL or the default here, the column silently loses them. Copy the current definition from SHOW CREATE TABLE customers first.
Renaming a table
PostgreSQL, MySQL, Oracle and SQLite use RENAME TO:
ALTER TABLE customers RENAME TO clients;MySQL also has a dedicated statement that can rename several tables in one atomic step:
RENAME TABLE customers TO clients, orders TO client_orders;SQL Server again uses sp_rename, this time without the third argument:
EXEC sp_rename 'customers', 'clients';What follows the rename and what does not
Databases keep internal references to objects. Whether those references follow a rename depends on the kind of object and on the database.
| Object that mentions the renamed item | PostgreSQL | MySQL 8 | SQL Server | SQLite 3.25+ |
|---|---|---|---|---|
| Foreign keys pointing at it | Follow | Follow | Follow | Follow |
| Indexes and primary key on it | Follow | Follow | Follow | Follow |
| Views that select from it | Updated automatically | Not updated; the view breaks | Not updated; the view breaks | Updated |
| Stored routines and triggers | Function bodies are text and are not checked | Not updated | Not updated | Triggers updated |
| Application queries and ORM mappings | Break | Break | Break | Break |
Check this table against your own version before relying on it. Behavior differs between versions. SQLite, for example, has a legacy_alter_table setting that changes it.
Two points are worth repeating:
- Foreign keys survive because they point at the table's identity inside the database, not at its text name. A rename never makes a foreign key invalid.
- Anything stored as plain text breaks silently. This includes SQL in your application, report definitions,
psqlscripts, dbt models, function bodies and ad hoc queries in a BI tool. The rename itself succeeds, and the failure appears later when one of those statements runs.
Seeing it in PostgreSQL
This script builds a table with a foreign key and a view, renames a column, and prints the view definition.
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL,
CONSTRAINT fk_orders_customer
FOREIGN KEY (customer_id) REFERENCES customers (id)
);
CREATE VIEW customer_names AS
SELECT id, name FROM customers;
ALTER TABLE customers RENAME COLUMN name TO full_name;
SELECT pg_get_viewdef('customer_names');The view still works. Its stored definition now reads customers.full_name AS name, so the view keeps exposing a column called name. The view's own output names do not change, so consumers of the view are not affected.
Names that do not change
A rename touches only the object you name. Objects created with automatic names keep the old text. After renaming customers to clients you will still see a primary key called customers_pkey in PostgreSQL. A serial column keeps a sequence called customers_id_seq.
This is harmless to the database but confusing to people. You can rename these objects too:
-- PostgreSQL
ALTER TABLE clients RENAME CONSTRAINT customers_pkey TO clients_pkey;
ALTER INDEX customers_email_idx RENAME TO clients_email_idx;
ALTER SEQUENCE customers_id_seq RENAME TO clients_id_seq;This is another reason to name constraints yourself when you create them, as fk_orders_customer does above. Explicit names that follow a convention are easier to find and fix.
Locking and transactions
A rename only edits the system catalog, so it runs in milliseconds regardless of table size. It still needs a strong lock. In PostgreSQL, ALTER TABLE ... RENAME takes an ACCESS EXCLUSIVE lock. The statement waits behind any running query on the table, and new queries then queue behind the rename. On a busy table, a rename stuck behind one long-running query can stall the whole application. Setting lock_timeout for the session lets the rename fail quickly instead of blocking everyone:
-- PostgreSQL
SET lock_timeout = '3s';
ALTER TABLE customers RENAME COLUMN name TO full_name;PostgreSQL also lets you roll back a rename that was done inside a transaction. MySQL commits implicitly around DDL, so a rename there cannot be undone with ROLLBACK. To undo it you run the reverse rename.
Renaming without breaking callers
On a live system, deploying a rename and updating every caller at the same instant is rarely possible. The usual approach is to change the name in steps (often called expand and contract):
Instead, use the diagram below to follow the steps.
For a table rename, a compatibility view is a lighter version of the same idea. Rename the table and create a view with the old name so existing queries keep working while you migrate callers:
ALTER TABLE customers RENAME TO clients;
CREATE VIEW customers AS SELECT * FROM clients;Simple views of this form accept inserts, updates and deletes in PostgreSQL and MySQL. In SQL Server and SQLite, test this before depending on it. Drop the view once nothing uses the old name.
Common mistakes
- Renaming and assuming the job is done. Search the application code, migrations, views, routines and dashboards for the old name before you run the rename.
- Using
CHANGEin old MySQL without the full definition. This silently dropsNOT NULL, defaults andAUTO_INCREMENT. - Putting the table name in the second argument of
sp_rename. This creates a badly named column. - Case surprises. In PostgreSQL, unquoted names fold to lowercase. Renaming to
"FullName"with quotes makes you quote it in every later query. Prefer lowercasesnake_case. - Renaming to make a type or meaning change. If a column is changing meaning, such as from
pricein dollars topricein cents, a rename does not fix it. Add a new column with a new name.
Exercise
In PostgreSQL, a view customer_names selects name from customers. You run ALTER TABLE customers RENAME COLUMN name TO full_name;. Does the view break? Would the same happen in MySQL 8, and what would you do about it there?
Show answer
In PostgreSQL the view keeps working, because its stored definition is rewritten to use customers.full_name AS name. In MySQL 8 the view is not updated and fails when queried, because its definition still refers to name. There you would re-create the view with CREATE OR REPLACE VIEW customer_names AS SELECT id, full_name AS name FROM customers; right after the rename, ideally in the same deployment step.
Exercise
Write the statements to rename the table orders to purchases in SQL Server, and then to rename its primary key constraint PK_orders to PK_purchases.
Show answer
EXEC sprename 'orders', 'purchases'; and then EXEC sprename 'PKorders', 'PKpurchases', 'OBJECT'; (a constraint is renamed as an object, and if the constraint is in a non-default schema you must qualify it, for example 'dbo.PK_orders'). The table rename does not change the constraint's name, so the second statement is needed.