// dialect comparison

DELETE rows matched in another table

Remove the orders of deleted customers: two tables, one DELETE, four syntaxes.

Filed under Inserting & updating

The verdict

PostgreSQL's USING is tidy, SQL Server and MySQL share the DELETE-alias join, and Oracle 23ai has its own FROM form. The subquery is the only version that runs unchanged on all five engines.

Where they differ

SQL Server and MySQL let a DELETE carry a join, naming the target alias right after DELETE. PostgreSQL has a USING clause, and Oracle 23ai a FROM clause. SQLite and older Oracle accept no join in DELETE, so they use an IN or EXISTS subquery, which runs on all five.

How each engine writes it

SQL Server

DELETE o
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE c.deleted = 1;

The alias after DELETE names the table whose rows go; extra joined tables stay read-only.

PostgreSQL

DELETE FROM orders o
USING customers c
WHERE c.id = o.customer_id
  AND c.deleted = 1;

USING is PostgreSQL's join clause for DELETE; only rows of the target table are ever removed.

MySQL

DELETE o
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE c.deleted = 1;

Same shape as SQL Server. MySQL also allows listing two targets (DELETE o, c FROM ...) to delete from both tables at once.

SQLite

DELETE FROM orders
WHERE customer_id IN (SELECT id FROM customers
                      WHERE deleted = 1);

No join in DELETE. The IN subquery is the portable form and reads just as well.

Oracle

DELETE FROM orders o
WHERE EXISTS (SELECT 1 FROM customers c
              WHERE c.id = o.customer_id
                AND c.deleted = 1);

Correlated EXISTS runs on every version. 23ai also accepts a join: DELETE orders o FROM customers c WHERE c.id = o.customer_id AND c.deleted = 1.

Questions that come up

Is the subquery form slower than the join?

Rarely. Current optimizers turn IN and EXISTS into the same semi-join an explicit join produces, so the plans usually match. Check the plan on very old MySQL versions, which handled IN subqueries in DELETE poorly.

Can I delete from two tables in one statement?

MySQL can, with a multi-table DELETE (DELETE o, c FROM …). PostgreSQL can chain data-modifying CTEs: WITH gone AS (DELETE FROM customers WHERE deleted = 1 RETURNING id) DELETE FROM orders WHERE customer_id IN (SELECT id FROM gone). Elsewhere, run two DELETEs in one transaction.

What about ON DELETE CASCADE instead?

If the foreign key is declared with ON DELETE CASCADE, deleting the parent rows removes the children with no join at all (see add-constraint). In SQLite that also requires PRAGMA foreign_keys = ON.

Keep reading

// write it once, run it anywhere

Switch engines without relearning SQL

SQLly is a native SQL workbench for macOS, Windows and Linux. Its formatter and plan viewer work in all five dialects.