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,215 days · since 2004
posts
294 · busiest 2026 (64)
words
~143,065 · ~10 h read
topics
tech 239 · personal 55
langs
en 229 · pl 65
written
211 by hand · 83 AI-assisted
projects
3
build
ca50768 · 2026-06-30