Become a Gold Sponsor

Drizzle query utils

$count

db.$count() is a utility wrapper of count(*), it is a very flexible operator which can be used as is or as a subquery, more details in our GitHub discussion.

const count = await db.$count(users);
//    ^? number

const count = await db.$count(users, eq(users.name, "Dan")); // works with filters
select count(*) from "users";
select count(*) from "users" where "name" = 'Dan';

It is exceptionally useful in subqueries:

const users = await db.select({
  ...users,
  postsCount: db.$count(posts, eq(posts.authorId, users.id)),
}).from(users);

usage example with relational queries

const users = await db.query.users.findMany({
  extras: {
    postsCount: db.$count(posts, eq(posts.authorId, users.id)),
  },
});