Example 1
Remove sessions belonging to banned users
User 2 appears in banned_users, so both of their sessions (ids 2 and 4) are deleted. Users 1 and 3 have no match in banned_users and their sessions remain. The correlated EXISTS subquery re-evaluates for each row in sessions, stopping as soon as a match is found.
CREATE TABLE sessions (id INT, user_id INT);
CREATE TABLE banned_users (user_id INT);
INSERT INTO
sessions (id, user_id)
VALUES
(1, 1),
(2, 2),
(3, 3),
(4, 2);
INSERT INTO
banned_users (user_id)
VALUES
(2);DELETE FROM sessions
WHERE
EXISTS (
SELECT
1
FROM
banned_users
WHERE
banned_users.user_id = sessions.user_id
);
SELECT
id,
user_id
FROM
sessions
ORDER BY
id;| id | user_id |
|---|---|
| 1 | 1 |
| 3 | 3 |
Output is identical across all engines.