Drizzle Count # of Records

What would be the best way to count records in drizzle? Thanks!
5 Replies
Liam
LiamOP2y ago
Tried this, but count returns as a string for some reason?
const totalUserCount = await db.select({ count: sql<number>`count(*)` }).from(users);
const totalUserCount = await db.select({ count: sql<number>`count(*)` }).from(users);
eatmoose
eatmoose2y ago
yes same here, i just cast it to number manually when i use it
adam-beck
adam-beck2y ago
Have you tried
const totalUserCount = await db.select({ count: sql<number>`count(*)`.mapWith(Number) }).from(users);
const totalUserCount = await db.select({ count: sql<number>`count(*)`.mapWith(Number) }).from(users);
Taken from here: https://orm.drizzle.team/docs/sql#sql-select
alexblokh
alexblokh2y ago
that's database driver dependent unfortunatelly and types are inferred and not mapped, so yes, example above with mapWith is correct
rphlmr ⚡
rphlmr ⚡2y ago
I made my "count" helper (Postgres)
export function count<Column extends AnyColumn>(column: Column) {
return sql<number>`cast(count(${column}) as integer)`;
}
export function count<Column extends AnyColumn>(column: Column) {
return sql<number>`cast(count(${column}) as integer)`;
}
Want results from more Discord servers?
Add your server