Rows Matching Every Required Tag
IN returns any-of matches; grouping joined tags and comparing HAVING count(DISTINCT tag) with the required count yields rows carrying every tag.
Code
CREATE TABLE posts (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL
);
CREATE TABLE post_tags (
post_id bigint REFERENCES posts,
tag text NOT NULL
);
INSERT INTO posts (title) VALUES
('Indexes deep dive'),
('CTE cookbook'),
('Window functions'),
('App deployment');
INSERT INTO post_tags VALUES
(1, 'sql'), (1, 'index'),
(2, 'sql'),
(3, 'sql'), (3, 'index'), (3, 'windows');
-- any-of: EXISTS with IN matches posts carrying at least one required tag
SELECT id, title FROM posts p
WHERE EXISTS (SELECT 1 FROM post_tags pt
WHERE pt.post_id = p.id AND pt.tag IN ('sql', 'index'));
-- all-of (relational division): rows matching EVERY required tag come from
-- grouping and requiring the distinct tag count to equal the list size
SELECT p.id, p.title
FROM posts p
JOIN post_tags pt ON pt.post_id = p.id
WHERE pt.tag IN ('sql', 'index')
GROUP BY p.id, p.title
HAVING count(DISTINCT pt.tag) = 2;The code at a glance — Rows Matching Every Required Tag
What runs here is SELECT / INSERT / CREATE — posts and post_tags are the objects involved.
The SQL constructs in play: one JOIN combining rows across tables; a WHERE clause limiting a statement to the rows that qualify; COUNT aggregation; a GROUP BY that collapses matching rows into one output row per group; a DISTINCT qualifier that collapses duplicate rows; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a GENERATED ALWAYS/GENERATED BY clause that computes the column value; a foreign-key REFERENCES guard anchoring child rows to their parent table.
Using it
The posts table is the working surface here.
Key statements
SELECT p.id, p.title
FROM posts p
JOIN post_tags pt ON pt.post_id = p.id
WHERE pt.tag IN ('sql', 'index')
GROUP BY p.id, p.title
HAVING count(DISTINCT pt.tag) = 2;
SELECT id, title FROM posts p
WHERE EXISTS (SELECT 1 FROM post_tags pt
WHERE pt.post_id = p.id AND pt.tag IN ('sql', 'index'));
INSERT INTO posts (title) VALUES
('Indexes deep dive'),
('CTE cookbook'),
('Window functions'),
('App deployment');
Interactive Tools for This Topic
FAQ
- Which objects does the SQL touch?
- The references are `posts`, `post_tags`, with one join tying the pair together.
Report a problem with this exampleOpens a pre-filled issue on GitHub.