Tag search
- SQL course
- Intermediate
- Lesson 85/115
- 5 min
Find posts with a tag using EXISTS.
Tag search
To find posts with a specific tag you use EXISTS.
SELECT title FROM posts p
WHERE EXISTS (SELECT 1 FROM post_tags t WHERE t.post_id = p.id AND t.tag = 'SQL');This query returns posts tagged SQL.
title is selected from posts p. WHERE keeps only the rows where EXISTS (SELECT 1 FROM post_tags t WHERE t.post_id = p.id … holds.
Tag search — details
EXISTS uses a correlated subquery. It stops at the first match, so it is fast.
For example, to list posts tagged "SQL" you check whether a matching row exists in the post_tags table.
Practice Tag search
Find posts tagged 'SQL' using EXISTS.
Starter code
-- tagged posts
SELECT title FROM posts p
WHERESample solution
SELECT title FROM posts p
WHERE EXISTS (SELECT 1 FROM post_tags t WHERE t.post_id = p.id AND t.tag = 'SQL');Expected output
title SQL temelleri JOIN rehberi
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is fast for tag search?
- DISTINCT
- COUNT
- IN
- EXISTS Correct answer
Explanation: EXISTS stops at the first match, so it is fast.
2 Add EXISTS
SELECT title FROM posts p
WHERE ____ (SELECT 1 FROM post_tags t WHERE t.post_id = p.id AND t.tag = 'SQL');
SELECT title FROM posts p
WHERE EXISTS (SELECT 1 FROM post_tags t WHERE t.post_id = p.id AND t.tag = 'SQL');
Explanation: EXISTS finds posts tagged SQL; the subquery is true once it finds at least one match.
3 Tag search: match the terms
| Term | Meaning |
|---|---|
EXISTS |
existence |
tag |
tag |
correlated |
outer-dependent |
fast |
short-circuit |