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.
Code
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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which objects does the SQL touch?
- `sessions` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.