테이블의 모든 행 개수를 세려면 아래와 같이 count() 함수 또는 sql 연산자를 사용할 수 있습니다:
index.ts
schema.ts
import { count, sql } from 'drizzle-orm';import { products } from './schema';const db = drizzle(...);await db.select({ count: count() }).from(products);// Under the hood, the count() function casts its result to a number at runtime.await db.select({ count: sql`count(*)`.mapWith(Number) }).from(products);
Drizzle은 간단하고 유연한 API를 제공하여 커스텀 솔루션을 만들 수 있습니다. PostgreSQL과 MySQL에서 count() 함수는 bigint를 반환하며, 드라이버에서 문자열로 해석되므로 정수로 캐스팅해야 합니다:
import { AnyColumn, sql } from 'drizzle-orm';const customCount = (column?: AnyColumn) => { if (column) { return sql<number>`cast(count(${column}) as integer)`; // In MySQL cast to unsigned integer } else { return sql<number>`cast(count(*) as integer)`; // In MySQL cast to unsigned integer }};await db.select({ count: customCount() }).from(products);await db.select({ count: customCount(products.discount) }).from(products);
select cast(count(*) as integer) from products;select cast(count("discount") as integer) from products;
select count(*) from products;select count("discount") from products;
IMPORTANT
sql<number>를 지정하면 필드의 예상 타입이 number라고 Drizzle에 알려주는 것입니다.
잘못 지정하면(예: 숫자로 반환될 필드에 sql<string> 사용) 런타임 값이 예상 타입과 일치하지 않습니다.
Drizzle은 제공된 타입 제네릭을 기반으로 타입 캐스팅을 수행할 수 없습니다. 해당 정보는 런타임에 사용할 수 없기 때문입니다.
반환된 값에 런타임 변환을 적용해야 하는 경우 .mapWith() 메서드를 사용할 수 있습니다.
조건에 맞는 행의 개수를 세려면 .where() 메서드를 사용할 수 있습니다:
import { count, gt } from 'drizzle-orm';await db .select({ count: count() }) .from(products) .where(gt(products.price, 100));
select count(*) from products where price > 100
조인 및 집계와 함께 count() 함수를 사용하는 방법은 다음과 같습니다:
index.ts
schema.ts
import { count, eq } from 'drizzle-orm';import { countries, cities } from './schema';// Count cities in each countryawait db .select({ country: countries.name, citiesCount: count(cities.id), }) .from(countries) .leftJoin(cities, eq(countries.id, cities.countryId)) .groupBy(countries.id) .orderBy(countries.name);
select countries.name, count("cities"."id") from countries left join cities on countries.id = cities.country_id group by countries.id order by countries.name;