Full answer
text
tags(id PK, name UNIQUE) -- normalise case: store lower(name)
item_tags(item_id FK, tag_id FK, PRIMARY KEY (item_id, tag_id))
CREATE INDEX ON item_tags (tag_id, item_id);Items with all of 'sql', 'joins' and 'beginner':
text
SELECT it.item_id FROM item_tags it JOIN tags t ON t.id = it.tag_id
WHERE t.name IN ('sql', 'joins', 'beginner')
GROUP BY it.item_id HAVING COUNT(DISTINCT t.id) = 3;Tag counts for a tag cloud come from GROUP BY tag_id and can be cached. Alternatives such as a comma-separated string or an array column (PostgreSQL text[] with a GIN index) are compact, but the junction table supports constraints, renames and statistics cleanly. Renaming a tag is then a single-row update. The all-tags query is shown for illustration and was not run here; COUNT(DISTINCT) matters because a tag listed twice in the IN list or duplicated in data would otherwise inflate the count.
Key points
- Tags plus a junction table
- Index both directions
- Any-of is a join with IN
- All-of is GROUP BY with HAVING COUNT
- Normalise tag case
Common mistakes
- Comma-separated tag strings
- Forgetting DISTINCT in the HAVING count
Follow-ups
- How would you suggest related tags?
- When is an array column acceptable?
Tips
- Show the all-tags query