Drizzle ORM & PostgreSQL - get rows from last N days

· Tech · No AI

Let’s say you have a table with timestamp column.

import { pgTable, product, serial, timestamp } from "drizzle-orm/pg-core";
export const purchases = pgTable("purchases", {
id: serial("id").primaryKey(),
created_at: timestamp("created_at", { withTimezone: true })
.defaultNow()
.notNull(),
product: text("product").notNull(),
});

You can get rows from last N days using sql operator and PostgreSQL INTERVAL operator.

await db
.select()
.from(profits)
.where(gt(profits.created_at, sql`NOW() - INTERVAL '7 days'`));

Drizzle will generate SQL like this:

select "id", "created_at", "product" from "purchases" where "purchases"."created_at" > NOW() - INTERVAL '7 days'
uptime
8,240 days · since 2004
posts
295 · busiest 2026 (65)
words
~144,041 · ~10 h read
topics
tech 240 · personal 55
langs
en 230 · pl 65
written
211 by hand · 84 AI-assisted
projects
3
build
ef72eda · 2026-07-24