© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
Drizzle TeamDT
Drizzle Team•3y ago•
1 reply
AstroBear

Using `count` in CTE has type `never`

I got the following tables:
users
users
:
id
id
, ...
followers
followers
:
followingId
followingId
,
followerId
followerId


I'm trying to write a
with
with
common table expression to reuse in other queries:
const withUser = db.$with('user').as(
    db
      .select({
        id: users.id,
        // ...
        following: countDistinct(following.followingId),
        followers: countDistinct(followers.followerId)
      })
      .from(users)
      .leftJoin(following, eq(following.followerId, users.id))
      .leftJoin(followers, eq(followers.followingId, users.id))
const withUser = db.$with('user').as(
    db
      .select({
        id: users.id,
        // ...
        following: countDistinct(following.followingId),
        followers: countDistinct(followers.followerId)
      })
      .from(users)
      .leftJoin(following, eq(following.followerId, users.id))
      .leftJoin(followers, eq(followers.followingId, users.id))


The problem is that now, if I try to use the results of that CTE,
sq.following
sq.following
and
sq.followers
sq.followers
are not valid columns:
const result = db
  .with(withUser)
  .select({ 
    following: withUser.following //< sq.following has type never, result[0].following is never
   })
  .from(withUser);
const result = db
  .with(withUser)
  .select({ 
    following: withUser.following //< sq.following has type never, result[0].following is never
   })
  .from(withUser);
Drizzle TeamJoin
The official Discord for all Drizzle related projects, such as Drizzle ORM, Drizzle Kit, Drizzle Studio and more!
11,879Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Getting type from a CTE
Drizzle TeamDTDrizzle Team / help
10mo ago
No CTE in generated SQL
Drizzle TeamDTDrizzle Team / help
3y ago
Re-using a CTE and typing hell
Drizzle TeamDTDrizzle Team / help
12mo ago
INSERT with CTE
Drizzle TeamDTDrizzle Team / help
2mo ago