Delete Using Join On Stale Rows

Delete the rows a grouped subquery selects with DELETE FROM ... USING, pruning expired sessions of over-limit users in one statement.

SqlData Integrity

Code

snippet
CREATE TABLE sessions (
    session_id int PRIMARY KEY,
    user_name  text NOT NULL,
    expires_at timestamptz NOT NULL
);

INSERT INTO sessions (session_id, user_name, expires_at) VALUES
    (1, 'ada', now() - interval '1 hour'),
    (2, 'lin', now() + interval '1 hour'),
    (3, 'ada', now() - interval '2 hours');

-- DELETE ... USING 联上分组子查询:删掉超限用户里已过期的行
DELETE FROM sessions s
USING (
    SELECT user_name
    FROM sessions
    GROUP BY user_name
    HAVING COUNT(*) > 1
) stale_users
WHERE s.user_name = stale_users.user_name
  AND s.expires_at < now()
RETURNING s.session_id, s.user_name;

SELECT session_id, user_name FROM sessions ORDER BY session_id;

DROP TABLE sessions;

How it works

Several statements share this file — SELECT / INSERT / DELETE / CREATE, with sessions among the objects involved.

What the statements actually assemble: a WHERE clause narrowing which rows one statement affects; COUNT aggregation; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order; a RETURNING clause that hands the affected rows back to the caller; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

Putting it to use

Run the statement against the sessions table.

Core lines

DELETE FROM sessions s
USING (
SELECT user_name
FROM sessions
GROUP BY user_name
HAVING COUNT(*) > 1
) stale_users
WHERE s.user_name = stale_users.user_name
AND s.expires_at < now()
RETURNING s.session_id, s.user_name;
INSERT INTO sessions (session_id, user_name, expires_at) VALUES
(1, 'ada', now() - interval '1 hour'),
(2, 'lin', now() + interval '1 hour'),
(3, 'ada', now() - interval '2 hours');
CREATE TABLE sessions (
session_id int PRIMARY KEY,
user_name  text NOT NULL,
expires_at timestamptz NOT NULL
);

Interactive Tools for This Topic

FAQ

Which objects does the SQL touch?
`sessions` — referenced directly, no join needed.