3091
MySQLERRORCommonData IntegrityHIGH confidence

TRUNCATE not allowed due to foreign key constraint

Production Risk

High — silently disabling FK checks can allow data integrity violations.

What this means

TRUNCATE TABLE cannot be performed because a foreign key constraint from another table references this table.

Why it happens
  1. 1Attempting TRUNCATE on a table that is the parent in an active foreign key relationship.
How to reproduce
trigger — this will error
trigger — this will error
TRUNCATE TABLE parent_table;  -- child_table has FK referencing parent_table

expected output

ERROR 3091 (HY000): Cannot truncate a table referenced in a foreign key constraint.

Fix 1

Disable foreign key checks, truncate, then re-enable

Disable foreign key checks, truncate, then re-enable
SET FOREIGN_KEY_CHECKS = 0;
TRUNCATE TABLE parent_table;
TRUNCATE TABLE child_table;
SET FOREIGN_KEY_CHECKS = 1;

Why this works

Bypasses the FK check for the duration of the truncation.

Fix 2

Delete child rows first, then truncate

Delete child rows first, then truncate
DELETE FROM child_table;
TRUNCATE TABLE parent_table;

Why this works

Removes dependent rows before truncating the parent.

What not to do

Sources
Official documentation ↗

MySQL 8.0 — 3091 ER_TRUNCATE_ILLEGAL_FK2

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All MySQL errors