import { eq } from "drizzle-orm";// Update single recordawait db .update(task) .set({ status: "complete", updatedAt: new Date(), }) .where(eq(task.id, taskId));// Update multiple recordsawait db .update(task) .set({ priority: 1 }) .where(eq(task.clientId, clientId));
Delete
// Delete single recordawait db .delete(task) .where(eq(task.id, taskId));// Delete with conditionawait db .delete(task) .where( and( eq(task.status, "cancelled"), lt(task.createdAt, oneYearAgo) ) );
Filtering
Basic Conditions
import { eq, ne, gt, gte, lt, lte } from "drizzle-orm";// Equalconst task = await db .select() .from(task) .where(eq(task.id, "task-123"));// Not equalconst activeTasks = await db .select() .from(task) .where(ne(task.status, "cancelled"));// Greater thanconst recentTasks = await db .select() .from(task) .where(gt(task.createdAt, lastWeek));
Combining Conditions
import { and, or } from "drizzle-orm";// AND - all conditions must be trueconst filteredTasks = await db .select() .from(task) .where( and( eq(task.clientId, clientId), eq(task.status, "in_progress"), gte(task.priority, 3) ) );// OR - any condition can be trueconst tasks = await db .select() .from(task) .where( or( eq(task.status, "complete"), eq(task.status, "cancelled") ) );
Pattern Matching
import { like, ilike } from "drizzle-orm";// Case-sensitive LIKEconst tasks = await db .select() .from(task) .where(like(task.title, "%website%"));// Case-insensitive ILIKE (PostgreSQL)const tasks = await db .select() .from(task) .where(ilike(task.title, "%website%"));
IN / NOT IN
import { inArray, notInArray } from "drizzle-orm";// IN - match any valueconst tasks = await db .select() .from(task) .where(inArray(task.status, ["in_progress", "awaiting_review"]));// NOT IN - exclude valuesconst tasks = await db .select() .from(task) .where(notInArray(task.status, ["cancelled", "complete"]));
NULL Checks
import { isNull, isNotNull } from "drizzle-orm";// Is NULLconst unassignedTasks = await db .select() .from(task) .where(isNull(task.pmId));// Is NOT NULLconst assignedTasks = await db .select() .from(task) .where(isNotNull(task.pmId));
try { await db.transaction(async (tx) => { await tx.insert(task).values({ ... }); // If this throws, everything rolls back if (someCondition) { throw new Error("Validation failed"); } await tx.insert(subtask).values({ ... }); });} catch (error) { console.error("Transaction failed:", error);}
Advanced Patterns
Conditional Queries
Build queries dynamically based on filters:
import { SQL, and } from "drizzle-orm";function buildTaskQuery(filters: { clientId?: string; status?: string; searchTerm?: string;}) { const conditions: SQL[] = []; if (filters.clientId) { conditions.push(eq(task.clientId, filters.clientId)); } if (filters.status) { conditions.push(eq(task.status, filters.status)); } if (filters.searchTerm) { conditions.push(ilike(task.title, `%${filters.searchTerm}%`)); } return db .select() .from(task) .where(conditions.length > 0 ? and(...conditions) : undefined);}// Usageconst tasks = await buildTaskQuery({ clientId: "client-123", status: "in_progress",});
Subqueries
import { sql } from "drizzle-orm";// Count subtasks per taskconst tasksWithSubtaskCount = await db .select({ task, subtaskCount: sql<number>`( SELECT COUNT(*) FROM ${subtask} WHERE ${subtask.taskId} = ${task.id} )`, }) .from(task);
Upsert (Insert or Update)
// PostgreSQL ON CONFLICTawait db .insert(userPreference) .values({ userId: "user-123", key: "theme", value: "dark", }) .onConflictDoUpdate({ target: [userPreference.userId, userPreference.key], set: { value: "dark", updatedAt: new Date() }, });
Batch Operations
// Insert in batches (more efficient for large datasets)const batchSize = 100;const records = [...]; // 1000s of recordsfor (let i = 0; i < records.length; i += batchSize) { const batch = records.slice(i, i + batchSize); await db.insert(timeEntry).values(batch);}