DDL Inside Transaction Rolls Back Too

Run CREATE TABLE and INSERT inside a transaction and roll it back: the table vanishes, proving DDL joins the same transactional story as DML.

SqlData Integrity

Code

snippet
BEGIN;

-- DDL 也参与事务:建表、插入、约束都在同一事务里
CREATE TABLE ddl_probe (
    id  int PRIMARY KEY,
    tag text NOT NULL
);
INSERT INTO ddl_probe VALUES (1, 'temp');

COMMIT;

SELECT count(*) FROM pg_class WHERE relname = 'ddl_probe';  -- 1:已提交

BEGIN;
CREATE TABLE ddl_probe2 (id int PRIMARY KEY);
ROLLBACK;

-- 回滚后表不存在:DDL 的效果跟着事务一起消失
SELECT count(*) FROM pg_class WHERE relname = 'ddl_probe2';  -- 0

How the snippet works

SELECT / INSERT / CREATE statements share the script, touching ddl_probe and pg_class.

Mechanically, the statements are built from: a WHERE clause narrowing which rows one statement affects; COUNT aggregation; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Applying it

The ddl_probe table is the working surface here.

Statements that matter

SELECT count(*) FROM pg_class WHERE relname = 'ddl_probe';  -- 1:已提交
SELECT count(*) FROM pg_class WHERE relname = 'ddl_probe2';  -- 0
CREATE TABLE ddl_probe (
    id  int PRIMARY KEY,
    tag text NOT NULL
);

Interactive Tools for This Topic

FAQ

What objects does the SQL involve?
`ddl_probe`, `pg_class`.