ALTER TABLE Rename Column And Table

RENAME COLUMN and RENAME TO are metadata-only changes: they take an ACCESS EXCLUSIVE lock, rewrite no data, and leave views referencing the old name broken.

SqlData Integrity

Code

snippet
-- 重命名是纯元数据操作:不重写行、不重建索引,只拿 ACCESS EXCLUSIVE 锁
CREATE TABLE customer_orders (
    id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    email text NOT NULL
);

INSERT INTO customer_orders (email) VALUES ('[email protected]');

-- RENAME COLUMN:依赖该列名的视图/函数不会自动跟随
ALTER TABLE customer_orders RENAME COLUMN email TO contact_email;

SELECT contact_email FROM customer_orders;

-- RENAME TO:改表名同样只动元数据;旧名立即失效
ALTER TABLE customer_orders RENAME TO orders;

INSERT INTO orders (contact_email) VALUES ('[email protected]');
SELECT id, contact_email FROM orders ORDER BY id;

-- 事务包裹可让改名与视图同步更新一起生效或一起回滚
BEGIN;
ALTER TABLE orders RENAME COLUMN contact_email TO email_addr;
ROLLBACK;
SELECT email FROM orders ORDER BY id;

Tracing the flow

The file runs SELECT / INSERT / CREATE / ALTER statements, touching customer_orders and orders.

Concretely, the SQL combines: an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Putting it to use

Run the statement against the customer_orders table.

Core lines

CREATE TABLE customer_orders (
    id    bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    email text NOT NULL
);
INSERT INTO customer_orders (email) VALUES ('[email protected]');
INSERT INTO orders (contact_email) VALUES ('[email protected]');

Interactive Tools for This Topic

FAQ

Which relations are involved here?
`customer_orders`, `orders` — referenced directly, no join needed.