Before continuing: This entry is part of the deleting data guide. If you are new to the topic, start with DELETE.
Query
To delete rows based on data in another table, you can use DELETE with JOIN/USING on engines that support it, or a WHERE EXISTS portable. The goal is to pick out rows in the table you are deleting from without accidentally making the helper table a deletion target too.
DELETE FROM payments
WHERE EXISTS (
SELECT 1
FROM orders AS p
WHERE p.id = payments.order_id
AND p.status = 'cancelled'
);This version expresses an existence check and works well when you only want to delete from payments.
Cases that change the result
Run the same filter with SELECT
SELECT pa.id, pa.order_id, pa.amount
FROM payments AS pa
JOIN orders AS p ON p.id = pa.order_id
WHERE p.status = 'cancelled'
ORDER BY pa.id;Count and review those rows before running the DELETE. If the result is not exactly what you expected, fix the JOIN or the filter, not the DELETE.
Cascades, triggers and transactions
A deleted row can trigger foreign keys with ON DELETE, triggers or other engine rules. The preview only shows the rows directly targeted; it is no substitute for checking side effects defined in the schema.
- Run the preview SELECT.
- Check foreign keys and cascades.
- Use a transaction when appropriate.
- Check the final state before committing.
Copying multi-table syntax from one engine to another
DELETE ... USING in PostgreSQL and DELETE alias FROM ... JOIN in MySQL/SQL Server look alike, but they are not interchangeable.
Key differences between engines
PostgreSQL: USING
DELETE FROM payments AS pa
USING orders AS p
WHERE p.id = pa.order_id
AND p.status = 'cancelled';USING brings in tables to look for matches; the table after DELETE FROM remains the target.
MySQL: DELETE with JOIN
DELETE pa
FROM payments AS pa
JOIN orders AS p ON p.id = pa.order_id
WHERE p.status = 'cancelled';MySQL also has multi-table syntax that can delete from more than one table at once. If you only mean to delete from payments, name only that alias as the target.
SQL Server: additional FROM
DELETE pa
FROM payments AS pa
JOIN orders AS p ON p.id = pa.order_id
WHERE p.status = 'cancelled';Transact-SQL supports a FROM clause to identify the rows to delete.
SQLite: EXISTS or IN
SQLite's documented syntax for DELETE does not include USING or a delete JOIN like PostgreSQL, MySQL or SQL Server. Use a subquery in WHERE, for example EXISTS.