General
Database

Client

Learn how to use basic database operations with the Drizzle database client.

The database client is powered by Drizzle, a type-safe and lightweight ORM. Drizzle provides a functional approach to database interactions, allowing you to query, create, update, and delete records with full TypeScript support.

This guide outlines core operations with the database client, such as querying, creating, updating, and deleting records. For in-depth details and advanced usage, visit the Drizzle ORM documentation.

Select records

To retrieve records from the database, you can use the db.select() method provided by Drizzle.

Here’s an example of how to query all contacts from the database:

query-records.ts
import { db, desc } from '@workspace/database/client';import { contactTable } from '@workspace/database/schema';const allContacts = await db  .select()  .from(contactTable)  .orderBy(desc(contactTable.createdAt));

Create record

To insert a new record into the database, you can use the db.insert() method and specify the table and values to be saved:

insert-record.ts
import { db } from '@workspace/database/client';import { contactTable } from '@workspace/database/schema';const contact = await db  .insert(contactTable)  .values({    name: 'John Doe',    email: 'john.doe@gmail.com'  })  .returning();

By default, Drizzle returns the full row. You can modify the return behavior using returning({}) to select specific fields.

Update record

To update an existing record, use the db.update() method, specifying the table, conditions, and data to update:

update-record.ts
import { db, eq } from '@workspace/database/client';import { contactTable } from '@workspace/database/schema';const updatedContact = await db  .update(contactTable)  .set({    name: 'John Doe Updated',    email: 'john.doe.updated@gmail.com'  })  .where(eq(contactTable.id, 'some-uuid'))  .returning();

You can use returning({}) to limit the returned fields and make the operation more efficient.

Delete record

To delete a record from the database, use the db.delete() method and specify the table and conditions:

delete-record.ts
import { db, eq } from '@workspace/database/client';import { contactTable } from '@workspace/database/schema';const deletedContact = await db  .delete(contactTable)  .where(eq(contactTable.id, 'some-uuid'))  .returning();

This will remove the record from the database permanently. You can use or omit returning({}) to limit the fields returned after the deletion if needed.