Filter parents with children
Return users only when a correlated posts subquery finds a matching post.
Drizzle ORM · Function
exists turns a Drizzle subquery into an SQL EXISTS condition. Use it in where to retain outer rows for which the subquery finds at least one result.
exists wraps a subquery as an SQL EXISTS predicate. The outer query keeps a row when the subquery produces at least one result, which is useful for testing whether a related record is present.
exists(subquery)| Name | Type | Description |
|---|---|---|
subquery | SQL query | A Drizzle select query used as the SQL subquery whose result presence is tested. |
A SQL boolean predicate representing whether the supplied subquery returns any rows.
exists from drizzle-orm alongside other filter operators.where clause.WHERE EXISTS expression around the supplied subquery.import { exists } from "drizzle-orm";
const postsByUser = db
.select({ id: posts.id })
.from(posts)
.where(eq(posts.userId, users.id));
const usersWithPosts = await db
.select()
.from(users)
.where(exists(postsByUser));Selects users for whom the correlated posts subquery finds at least one matching row.
Return users only when a correlated posts subquery finds a matching post.
Check whether a matching row exists without returning child columns.
Avoid multiplying parent result rows when several child rows match.
exists do?exists converts a subquery into an existence predicate. The outer row is retained when the subquery returns at least one row, producing SQL such as WHERE EXISTS (SELECT ...).
Follow-up: How would you find users with posts? Answer: correlate the subquery by comparing the child foreign key with the outer user's key, then pass that subquery to exists.
Build a subquery from the child table, correlate it to the outer table with a filter, and apply exists in the outer query's where clause. This returns only parents having a matching child.
Follow-up: What should the subquery select? Answer: only a small marker such as sql\1\ when child data is not needed.
exists preferable to an inner join?Use an inner join when the result must include related child data. Use exists when the requirement is only to test whether a related row is present and return the parent rows.
Follow-up: Why can exists avoid duplicate parents? Answer: it tests presence rather than adding one output row for every matching child.
notExistseqsqlinnerJoinselect