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.

SqlData Integrity

Code

snippet
-- 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

FAQ

Which tables or CTEs does it reference?
The references are `users`.