Drizzle | SQL Increment value
PostgreSQL
MySQL
SQLite
This guide assumes familiarity with:
- Get started with PostgreSQL, MySQL and SQLite
- Update statement
- Filters and sql operator
To increment a column value you can use update().set()
method like below:
import { eq, sql } from 'drizzle-orm';
const db = drizzle(...)
await db
.update(table)
.set({
counter: sql`${table.counter} + 1`,
})
.where(eq(table.id, 1));
update "table" set "counter" = "counter" + 1 where "id" = 1;
Drizzle has simple and flexible API, which lets you easily create custom solutions. This is how you do custom increment function:
import { AnyColumn } from 'drizzle-orm';
const increment = (column: AnyColumn, value = 1) => {
return sql`${column} + ${value}`;
};
await db
.update(table)
.set({
counter1: increment(table.counter1),
counter2: increment(table.counter2, 10),
})
.where(eq(table.id, 1));