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.
Code
-- 重命名是纯元数据操作:不重写行、不重建索引,只拿 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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.CSV Column AnalyzerProfile every CSV column with inferred types, empty-cell counts, unique values, and numeric min and max ranges.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- Which relations are involved here?
- `customer_orders`, `orders` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.