Become a Gold Sponsor

Type API

To retrieve a type from your table schema for select and insert queries, you can make use of our type helpers.

PostgreSQL
MySQL
SQLite
import { serial, text, pgTable } from 'drizzle-orm/pg-core';
import { type InferSelectModel, type InferInsertModel } from 'drizzle-orm'

const users = pgTable('users', {
  id: serial('id').primaryKey(),
  name: text('name').notNull(),
});

type SelectUser = typeof users.$inferSelect;
type InsertUser = typeof users.$inferInsert;
// or
type SelectUser = typeof users._.$inferSelect;
type InsertUser = typeof users._.$inferInsert;
// or
type SelectUser = InferSelectModel<typeof users>;
type InsertUser = InferInsertModel<typeof users>;

Logging

To enable default query logging, just pass { logger: true } to the drizzle initialization function:

import { drizzle } from 'drizzle-orm/...'; // driver specific

const db = drizzle({ logger: true });

You can change the logs destination by creating a DefaultLogger instance and providing a custom writer to it:

import { DefaultLogger, LogWriter } from 'drizzle-orm/logger';
import { drizzle } from 'drizzle-orm/...'; // driver specific

class MyLogWriter implements LogWriter {
  write(message: string) {
    // Write to file, stdout, etc.
  }
}

const logger = new DefaultLogger({ writer: new MyLogWriter() });
const db = drizzle({ logger });

You can also create a custom logger:

import { Logger } from 'drizzle-orm/logger';
import { drizzle } from 'drizzle-orm/...'; // driver specific

class MyLogger implements Logger {
  logQuery(query: string, params: unknown[]): void {
    console.log({ query, params });
  }
}

const db = drizzle({ logger: new MyLogger() });

Multi-project schema

Table creator API lets you define customise table names.
It’s very useful when you need to keep schemas of different projects in one database.

PostgreSQL
MySQL
SQLite
import { serial, text, pgTableCreator } from 'drizzle-orm/pg-core';

const pgTable = pgTableCreator((name) => `project1_${name}`);

const users = pgTable('users', {
  id: serial('id').primaryKey(),
  name: text('name').notNull(),
});
import { defineConfig } from "drizzle-kit";

export default defineConfig({
  schema: "./src/schema/*",
  out: "./drizzle",
  dialect: "mysql", 
  dbCredentials: {
    url: process.env.DATABASE_URL,
  }
  tablesFilter: ["project1_*"],
});

You can apply multiple or filters:

tablesFilter: ["project1_*", "project2_*"]

Printing SQL query

You can print SQL queries with db instance or by using standalone query builder.

const query = db
  .select({ id: users.id, name: users.name })
  .from(users)
  .groupBy(users.id)
  .toSQL();
// query:
{
  sql: 'select 'id', 'name' from 'users' group by 'users'.'id'',
  params: [],
}

Raw SQL queries execution

If you have some complex queries to execute and drizzle-orm can’t handle them yet, you can use the db.execute method to execute raw parametrized queries.

PostgreSQL
MySQL
SQLite
const statement = sql`select * from ${users} where ${users.id} = ${userId}`;
const res: postgres.RowList<Record<string, unknown>[]> = await db.execute(statement)

Standalone query builder

Drizzle ORM provides a standalone query builder that allows you to build queries without creating a database instance and get generated SQL.

PostgreSQL
MySQL
SQLite
import { QueryBuilder } from 'drizzle-orm/pg-core';

const qb = new QueryBuilder();

const query = qb.select().from(users).where(eq(users.name, 'Dan'));
const { sql, params } = query.toSQL();

Get typed table columns

You can get a typed table columns map, very useful when you need to omit certain columns upon selection.

PostgreSQL
MySQL
SQLite
index.ts
schema.ts
import { getTableColumns } from "drizzle-orm";
import { user } from "./schema";

const { password, role, ...rest } = getTableColumns(user);

await db.select({ ...rest }).from(users);

Get table information

PostgreSQL
MySQL
SQLite
import { getTableConfig, pgTable } from 'drizzle-orm/pg-core';

export const table = pgTable(...);

const {
  columns,
  indexes,
  foreignKeys,
  checks,
  primaryKeys,
  name,
  schema,
} = getTableConfig(table);

Compare objects types (instanceof alternative)

You can check if an object is of a specific Drizzle type using the is() function. You can use it with any available type in Drizzle.

IMPORTANT

You should always use is() instead of instanceof

Few examples

import { Column, is } from 'drizzle-orm';

if (is(value, Column)) {
  // value's type is narrowed to Column
}

Mock Driver

This API is a successor to an undefined drizzle({} as any) API which we’ve used internally in Drizzle tests and rarely recommended to external developers.

We decided to build and expose a proper API, every drizzle driver now has drizzle.mock():

import { drizzle } from "drizzle-orm/node-postgres";

const db = drizzle.mock();

you can provide schema if necessary for types

import { drizzle } from "drizzle-orm/node-postgres";
import * as schema from "./schema"

const db = drizzle.mock({ schema });