MySQL, Error Code: 1093. You can’t specify target table for update in FROM clause
The error you’re encountering, “Error Code: 1093. You can’t specify target table ‘tableName’ for an update in FROM clause”, occurs when you try to update a table based on a subquery referencing the same table. MySQL doesn’t allow updates to a table when the table is also being used in a subquery in the FROM clause.
You can use a temporary table or nest the subquery to work around this limitation. Here are both methods explained:
Method 1: Using a Temporary Table
- Step 1: Create a temporary table and insert the necessary data from the original table.
CREATE TEMPORARY TABLE TempOrders AS
SELECT * FROM TableName WHERE [Your Condition];
- Step 2: Perform the update using the temporary table.
UPDATE TableName
SET Orders.column_name = [New Value]
WHERE Orders.column_name IN (SELECT column_name FROM TempOrders);
- Step 3: Drop the temporary table (optional).
DROP TEMPORARY TABLE TempOrders;
Method 2: Using a Nested Subquery
Use a nested subquery to isolate the reference to the target table.
UPDATE TableName
SET column_name = [New Value]
WHERE column_name IN (
SELECT * FROM (
SELECT column_name FROM TableName WHERE [Your Condition]
) AS Temp
);
In both methods, replace column_name
with the actual column name you’re working with, [Your Condition]
with the actual condition for selecting rows and [New Value]
with the new value you want to set.