sqlcmd.net validated sql reference
intermediate updating MySQL MariaDB SQL Server PostgreSQL SQLite

Update Rows Selected By A Subquery

Use a subquery in the `WHERE` clause of an `UPDATE` to restrict which rows are modified based on data from another table.

Docker-validated Not currently validation-green

Mark orders as shipped for all customers based in the US

The subquery returns customer IDs 1 and 3 (Alice and Carol, both in the US). The UPDATE sets status = 'shipped' for orders 1 and 3, which belong to those customers. Order 2 (Bob, Canada) is untouched and remains pending.

Rows loaded before the example query runs.
Setup
CREATE TABLE customers (id INT, name VARCHAR(50), country VARCHAR(10));

INSERT INTO
  customers
VALUES
  (1, 'Alice', 'US'),
  (2, 'Bob', 'CA'),
  (3, 'Carol', 'US');

CREATE TABLE orders (id INT, customer_id INT, status VARCHAR(20));

INSERT INTO
  orders
VALUES
  (1, 1, 'pending'),
  (2, 2, 'pending'),
  (3, 3, 'pending');
Shared across supported engines.
SQL
UPDATE orders
SET
  status = 'shipped'
WHERE
  customer_id IN (
    SELECT
      id
    FROM
      customers
    WHERE
      country = 'US'
  );

SELECT
  id,
  status
FROM
  orders
ORDER BY
  id;
Returned rows for the shared example.
idstatus
1shipped
2pending
3shipped

Identical syntax and result across all engines.

Where this command helps.

  • changing the status of all orders belonging to customers in a specific region
  • applying a bulk update to rows that match a condition in a separate lookup table

What the command is doing.

A subquery in UPDATE ... WHERE col IN (SELECT ...) lets you target rows based on a condition that involves another table without writing a join. This is useful for batch status changes, bulk flag updates, or cascading changes driven by a lookup table. The subquery runs first and produces a set of values; the UPDATE then touches only rows whose column matches one of those values. For large datasets, rewriting as UPDATE ... JOIN (MySQL/MariaDB) or UPDATE ... FROM (PostgreSQL/SQL Server) can be more efficient.