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.
Code
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'; -- 0How 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
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.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.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What objects does the SQL involve?
- `ddl_probe`, `pg_class`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.