Convert a Basic SQL Table to Drizzle Schema
Learn how to convert a simple SQL CREATE TABLE statement into a Drizzle ORM table definition. Covers column builders, notNull, and table export conventions.
Detailed Explanation
From CREATE TABLE to Drizzle Table Definition
The most fundamental conversion takes a SQL CREATE TABLE statement and produces a Drizzle table definition using the appropriate dialect function (pgTable, mysqlTable, or sqliteTable). Each column becomes a call to a column builder function, and constraints are expressed as chained methods.
Example SQL
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) NOT NULL,
bio TEXT,
is_active BOOLEAN NOT NULL DEFAULT true
);
Generated Drizzle Schema (PostgreSQL)
import { boolean, pgTable, serial, text, varchar } from "drizzle-orm/pg-core";
export const users = pgTable("users", {
id: serial("id").primaryKey(),
name: varchar("name", { length: 100 }).notNull(),
email: varchar("email", { length: 255 }).notNull(),
bio: text("bio"),
isActive: boolean("is_active").default(true).notNull(),
});
Key Concepts
| SQL Element | Drizzle Equivalent |
|---|---|
| Table name | First argument to pgTable() |
| Column name | First argument to the column builder |
NOT NULL |
.notNull() chain |
| Nullable column | No .notNull() (default behavior) |
PRIMARY KEY |
.primaryKey() chain |
DEFAULT |
.default(value) chain |
Import Generation
Drizzle requires explicit imports for each column builder. The converter analyzes which builders are needed and generates a single import statement from the correct dialect module. Only the builders actually used in your schema are included, keeping the imports clean.
Variable Naming
The exported table variable uses camelCase derived from the SQL table name. For example, user_accounts becomes userAccounts. The original SQL table name is preserved as the first string argument to the table function.
Use Case
You have an existing PostgreSQL, MySQL, or SQLite database and want to start using Drizzle ORM. Instead of manually writing the schema file, paste your CREATE TABLE statements to get a ready-to-use Drizzle schema.