TRUNCATE With Foreign Keys RESTART IDENTITY
Empty tables fast with TRUNCATE RESTART IDENTITY, see why a foreign key reference blocks it, and use CASCADE plus a transaction for a safe purge.
Code
-- TRUNCATE 一步清空全表并重置 identity/serial 序列,
-- 不逐行扫表、不触发行级 ON DELETE 触发器
SELECT count(*) AS rows_before FROM users;
TRUNCATE users RESTART IDENTITY;
SELECT count(*) AS rows_after FROM users;
-- 表被外键引用时直接拒绝:
-- ERROR: cannot truncate a table referenced in a foreign key constraint
-- DETAIL: Table "orders" references "users".
TRUNCATE users;
-- CASCADE 连带清空所有引用该表的子表
TRUNCATE users CASCADE;
-- 一次 TRUNCATE 多表 + 重置序列 + 连带子表,幂等地重建测试数据
TRUNCATE users, orders, order_items RESTART IDENTITY CASCADE;
-- TRUNCATE 是事务性的:包在事务里可以整体回滚
BEGIN;
TRUNCATE users RESTART IDENTITY;
ROLLBACK;How it works
Several statements share this file — SELECT, with users among the objects involved.
Breaking the statements into their working parts: COUNT aggregation.
Applying it
The users table is the working surface here.
Statements that matter
SELECT count(*) AS rows_before FROM users;
SELECT count(*) AS rows_after FROM users;
TRUNCATE users, orders, order_items RESTART IDENTITY CASCADE;
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
- Which tables or CTEs does it reference?
- The references are `users`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.