Drizzle PostgreSQL Query Builder Joins
Type-safe joins with the Drizzle query builder against PostgreSQL, mapping result rows to inferred shapes and parameterizing every input.
Code
import { pgTable, serial, text, integer, timestamp } from 'drizzle-orm/pg-core';
import { drizzle } from 'drizzle-orm/node-postgres';
import { eq, gte, desc, and, sql } from 'drizzle-orm';
import { Pool } from 'pg';
const customers = pgTable('customers', {
id: serial('id').primaryKey(),
email: text('email').notNull(),
});
const orders = pgTable('orders', {
id: serial('id').primaryKey(),
customerId: integer('customer_id').notNull(),
total: integer('total').notNull(),
createdAt: timestamp('created_at').defaultNow(),
});
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const db = drizzle(pool);
async function recentBigOrders(minTotal: number) {
const rows = await db
.select({
orderId: orders.id,
email: customers.email,
total: orders.total,
})
.from(orders)
.innerJoin(customers, eq(orders.customerId, customers.id))
.where(and(gte(orders.total, minTotal)))
.orderBy(desc(orders.createdAt))
.limit(50);
return rows;
}
const qualified = await recentBigOrders(1000);
console.log('rows typed:', qualified[0]?.email.length ?? 0);
await pool.end();How it works
recentBigOrders holds the query logic; the pgTable definitions around it are wiring.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. pgTable, serial, text, integer, timestamp are the only symbols borrowed from drizzle-orm/pg-core — the coupling is explicit and narrow.
Tunables arrive as environment variables: DATABASE_URL.
What to watch for
drizzle-orm/pg-core,drizzle-orm/node-postgresanddrizzle-ormmust be installed first — the snippet imports them directly.
Using it
The primary signature is async function recentBigOrders(minTotal: number)
Running the file prints labeled results such as rows typed: — printed by recentBigOrders after the join runs.
Key statements
const qualified = await recentBigOrders(1000);
await pool.end();
const rows = await db
.select({
orderId: orders.id,
email: customers.email,
total: orders.total,
})
.from(orders)
.innerJoin(customers, eq(orders.customerId, customers.id))
.where(and(gte(orders.total, minTotal)))
.orderBy(desc(orders.createdAt))
.limit(50);
Interactive Tools for This Topic
FAQ
- Do I need to install anything before running this?
- Yes: `drizzle-orm/pg-core`, `drizzle-orm/node-postgres` and `drizzle-orm` must be present in the project or the import fails at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.