SQL
Filtering Records Using EXISTS Subqueries
Learn to use the SQL EXISTS operator within a subquery to efficiently retrieve records from one table only if corresponding entries exist in another, optimizing complex conditional selections.
SELECT
p.post_id,
p.title,
p.created_at
FROM
posts p
WHERE EXISTS (
SELECT 1
FROM comments c
WHERE c.post_id = p.post_id
AND c.status = 'approved'
);
How it works: This query retrieves posts that have at least one approved comment. The `EXISTS` operator is used to check for the presence of any row returned by the subquery. It's often more efficient than a `JOIN` when you only need to verify existence rather than retrieve data from the joined table. The subquery returns '1' if an approved comment for the current post exists, and `EXISTS` evaluates to true, including the post in the result set.