1941
MySQLERRORCriticalStored RoutinesHIGH confidence

Cannot modify a table that is being used by a stored function or trigger

Production Risk

High — business logic in the trigger will silently fail to execute.

What this means

A stored function or trigger attempted to modify a table that is already being read or written in the calling statement. MySQL prohibits this to prevent non-deterministic behavior.

Why it happens
  1. 1A trigger on table T tries to INSERT or UPDATE table T (same table).
  2. 2A stored function called in a SELECT modifies a table read by that SELECT.
How to reproduce
trigger — this will error
trigger — this will error
-- Trigger on orders tries to INSERT into orders
CREATE TRIGGER t AFTER INSERT ON orders FOR EACH ROW INSERT INTO orders VALUES(NEW.id+1000);

expected output

ERROR 1941 (HY000): Cannot modify a table that is being used by a stored function or trigger that invoked this statement.

Fix

Avoid modifying the same table inside a trigger on that table

Avoid modifying the same table inside a trigger on that table
-- Use a separate audit or log table instead
CREATE TRIGGER t AFTER INSERT ON orders FOR EACH ROW INSERT INTO order_log VALUES(NEW.id);

Why this works

Write side-effects to a different table to avoid the restriction.

What not to do

Sources
Official documentation ↗

MySQL 8.0 — 1941 ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG

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

← All MySQL errors