A subquery inside an UPDATE statement lets you compute new values or filter rows dynamically based on other data in the database. This is useful when the logic is too complex for a simple JOIN or when you need to reference aggregate results.
Subquery in SET Clause
You can use a scalar subquery in the SET clause to compute the new value for a column. The subquery must return exactly one row and one column. If it returns no rows, NULL is assigned.
Subquery in WHERE Clause
A subquery in the WHERE clause filters which rows to update. For example, you can update all products whose category ID matches a list returned by another SELECT statement.
- Use EXISTS or IN for correlated subqueries in WHERE
- Scalar subqueries in SET must return a single value
- MySQL does not allow you to SELECT from the same table you are updating directly — use a derived table workaround