Drizzle ORM provides a TypeScript-native schema definition and query builder that compiles directly to SQL. UUID v7 primary keys integrate through the uuid() column helper with a PostgreSQL-side default, delivering chronological ordering and cursor pagination without any ORM-layer changes. See UUID in Databases for the storage fundamentals.
Install dependencies
npm install drizzle-orm drizzle-kit postgres uuid
npm install -D @types/uuid
Enable pg_uuidv7 in PostgreSQL
-- Run once in your database (Supabase, Neon, or self-hosted PostgreSQL 14+)
CREATE EXTENSION IF NOT EXISTS "pg_uuidv7";
Drizzle schema definition
// schema.ts
import { pgTable, uuid, text, numeric, timestamp } from 'drizzle-orm/pg-core';
import { sql } from 'drizzle-orm';
export const orders = pgTable('orders', {
id: uuid('id').primaryKey().default(sql`gen_random_uuid_v7()`),
customerId: uuid('customer_id').notNull(),
status: text('status').notNull().default('pending'),
total: numeric('total', { precision: 10, scale: 2 }).notNull(),
});
export const orderItems = pgTable('order_items', {
id: uuid('id').primaryKey().default(sql`gen_random_uuid_v7()`),
orderId: uuid('order_id').notNull().references(() => orders.id),
sku: text('sku').notNull(),
quantity: numeric('quantity').notNull(),
});
Database connection
// db.ts
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import * as schema from './schema';
const client = postgres(process.env.DATABASE_URL!);
export const db = drizzle(client, { schema });
Insert with UUID v7 (client-side)
import { db } from './db';
import { orders } from './schema';
import { v7 as uuidv7 } from 'uuid';
// Client-generated UUID v7 — encodes insert time
async function createOrder(customerId: string, total: number) {
const id = uuidv7();
const [order] = await db
.insert(orders)
.values({ id, customerId, total: total.toFixed(2) })
.returning();
return order;
}
// Database-generated UUID v7 (uses gen_random_uuid_v7() default)
async function createOrderDbDefault(customerId: string, total: number) {
const [order] = await db
.insert(orders)
.values({ customerId, total: total.toFixed(2) })
.returning(); // id will be a UUID v7 from PostgreSQL
return order;
}
Cursor pagination
import { gt, asc, eq, and } from 'drizzle-orm';
import { db } from './db';
import { orders } from './schema';
async function listOrders(customerId: string, cursor?: string, limit = 20) {
const conditions = cursor
? and(eq(orders.customerId, customerId), gt(orders.id, cursor))
: eq(orders.customerId, customerId);
const rows = await db
.select()
.from(orders)
.where(conditions)
.orderBy(asc(orders.id)) // UUID v7 lexicographic = chronological
.limit(limit + 1);
const hasMore = rows.length > limit;
const data = hasMore ? rows.slice(0, limit) : rows;
const nextCursor = hasMore ? data.at(-1)!.id : null;
return { data, nextCursor };
}
Extract timestamp from UUID v7 column
import { sql } from 'drizzle-orm';
import { db } from './db';
import { orders } from './schema';
// Use PostgreSQL uuid_extract_timestamp() from pg_uuidv7 extension
async function getOrdersWithTimestamps() {
return db.select({
id: orders.id,
status: orders.status,
createdAt: sql<Date>`uuid_extract_timestamp(${orders.id})`,
}).from(orders).orderBy(orders.id);
}
// Client-side extraction — no SQL function needed
function extractTimestampFromUuidV7(id: string): Date {
const hex = id.replace(/-/g, '').slice(0, 12);
return new Date(parseInt(hex, 16));
}
Time-range query using UUID v7
import { sql } from 'drizzle-orm';
// Orders in the last 24 hours — no created_at column needed
async function recentOrders() {
return db.select()
.from(orders)
.where(
sql`uuid_extract_timestamp(${orders.id}) > now() - interval '24 hours'`
)
.orderBy(orders.id);
}
Drizzle migration
// drizzle.config.ts
import { defineConfig } from 'drizzle-kit';
export default defineConfig({
schema: './schema.ts',
out: './migrations',
driver: 'pg',
dbCredentials: { connectionString: process.env.DATABASE_URL! },
});
Generated migration includes DEFAULT gen_random_uuid_v7() for UUID v7 columns.
Further reading
- UUID v7 in Prisma + PostgreSQL
- UUID v7 for Cursor Pagination
- UUID v7 in Supabase Realtime
- UUID v7 in Kysely
- UUID in Databases — Storage and Indexing
External references
Frequently asked questions
How do I define a UUID v7 primary key in Drizzle ORM?
Use uuid('id').primaryKey().defaultRandom() and override the default to gen_random_uuid_v7() using a custom SQL default: uuid('id').primaryKey().default(sql`gen_random_uuid_v7()`). This requires the pg_uuidv7 extension to be installed in PostgreSQL. See UUID v7 in Prisma + PostgreSQL for the Prisma equivalent.
How do I extract the creation timestamp from a UUID v7 column in Drizzle?
Use the PostgreSQL function uuid_extract_timestamp(id) from the pg_uuidv7 extension in a raw SQL fragment: sql<Date>`uuid_extract_timestamp(${table.id})`. This returns a TIMESTAMPTZ. On the client side, parse the UUID string directly: first 12 hex digits of the stripped UUID encode Unix milliseconds. See UUID v7 in Prisma + PostgreSQL.
How do I implement cursor pagination with UUID v7 in Drizzle?
Query where(gt(table.id, cursor)) and orderBy(asc(table.id)). UUID v7 is lexicographically sorted, so id > cursor in string comparison equals created_after(cursor). The last row's id becomes the next cursor — no created_at column needed. See UUID v7 for Cursor Pagination.