Insert
insert() adds rows. Pass a single object or an array for multi-row insert.
Both compile to a single bound-parameter statement.
Insert one row
Section titled “Insert one row”await db.from(users).insert({ email: "ada@example.com", age: 36 });Insert many rows
Section titled “Insert many rows”await db.from(users).insert([ { email: "a@b.c", age: 20 }, { email: "c@d.e", age: 30 },]);Read back with returning()
Section titled “Read back with returning()”Chain .returning(...) to get the inserted row(s), including generated IDs:
const { rows } = await db.from(users).returning("id", "email").insert({ email: "ada@example.com",});// rows[0].id is the generated primary keyHow it compiles
Section titled “How it compiles”db.from(users).insert({ email: "a@b.c" });// → INSERT INTO "users" ("email") VALUES (?)Real-world example
Section titled “Real-world example”export async function createUser(email: string, age: number) { const { rows } = await db.from(users).returning("id").insert({ email, age }); return rows[0].id;}Best practices
Section titled “Best practices”- Use multi-row insert for bulk loads — one statement, many params.
- Use
returning("id")when you need the generated key. - Let
InferTabletype the values you pass.
Common mistakes
Section titled “Common mistakes”- Awaiting
insertbut ignoring the returnedrowswhen you need the ID. - Hand-building a multi-row statement instead of passing an array.
