In general I like to use COUNT(*) OVER ()
to get the total count for a query when retrieving a slice with OFFSET and LIMIT (very useful for pagination) rather than issuing a separate query for the total count. This is not super well supported in Drizzle but you can do it like this:
const data = await db.query.tableName.findMany({ … extras: { // Weird cast here because COUNT(*) is a bigint which is handled as a string in js // https://orm.drizzle.team/docs/guides/count-rows total: sql<number>`CAST(COUNT(*) OVER() AS INTEGER)`.as("total"), }, …