❯ehsan.blog
~/blog/your-drizzle-table-has-two-row-types-not-one — zsh
❯cat your-drizzle-table-has-two-row-types-not-one.md

Your Drizzle table has two row types, not one

·8 min read

Your Drizzle table has two row types, not one — article card for a post by Ehsan Shahid

You define a table once. Drizzle hands you back two different shapes for it, and they disagree about which columns you are allowed to leave out.

That sounds like a detail. It cost me an afternoon.

Here is the table:

ts
const posts = pgTable('posts', {
  id: serial('id').primaryKey(),
  title: text('title').notNull(),
  publishedAt: timestamp('published_at'),
})

Three columns. Now a fair question: in “the Post type”, is id required?

There is no single answer, because there is no single Post type.

Drizzle’s two row types

Every Drizzle table exposes two inferred types:

  • typeof posts.$inferSelect — the shape of a row you read from the database.
  • typeof posts.$inferInsert — the shape of an object you write into it.

Most people grab one of them, name it Post, and use it everywhere. I did exactly that, and I picked the wrong one.

flowchart LR
    A["one column:<br/>publishedAt: timestamp()"] --> B["$inferSelect<br/>publishedAt: Date | null<br/>(always present)"]
    A --> C["$inferInsert<br/>publishedAt?: Date | null<br/>(may be omitted)"]

The bug I shipped: I used $inferInsert as the type for rows coming out of a query. TypeScript was happy. id on that type is optional, so every place that read post.id silently widened to number | undefined and nothing complained until a .toString() hit undefined at runtime.

The reverse mistake is louder. Use $inferSelect for an insert and TypeScript demands an id you do not have yet, because the database generates it.

The rule, written down

I went into the source rather than guessing. In drizzle-orm the select shape is one plain mapped type, and GetColumnData in column.d.ts decides the value:

ts
TColumn['_']['notNull'] extends true
  ? TColumn['_']['data']
  : TColumn['_']['data'] | null

Read that carefully, because it is the part people get backwards. On select, nullability changes the value type — you get Date | null. It never makes the key optional. Every column you defined comes back on every row. A row that came out of Postgres has a value for each column, and sometimes that value is null.

Insert works on a completely different mechanism. It is two mapped types intersected, and the keys are remapped through these helpers in operations.d.ts:

ts
type RequiredKeyOnly<TKey, T> =
  T extends AnyColumn<{ notNull: true; hasDefault: false }> ? TKey : never

So a column is required on insert only when both things hold: it is notNull, and it has no default. Everything else lands in the optional bucket.

That single line explains the whole thing:

ColumnOn selectOn insert
text('a').notNull()a: stringa: string — required
text('b')b: string | nullb?: string | null — optional
text('c').notNull().default('x')c: stringc?: string — optional
serial('id').primaryKey()id: numberid?: number — optional

Row three is the one that surprises people. .notNull().default('x') is required in the database and optional in your insert type, and both are correct — you may omit it precisely because the database will fill it in. serial().primaryKey() is the same story, which is why id is optional on insert.

If you are new to this, here is the sentence that makes it click. “Required” and “nullable” are answers to two different questions, and Drizzle asks a different one on each side.

On the way in, the question is do I have to type this myself? A column with a default answers no, even when the database refuses to store a null there. On the way out, the question is will this key exist on the object I get back? The answer is always yes, because a database row has a slot for every column. Whether that slot holds a value or a null is a separate matter, and that is the part the type expresses as | null.

Mix the two questions up and you get the exact confusion I had: “the column is NOT NULL, so why is TypeScript letting me skip it?” Because NOT NULL is a promise about what ends up stored, not a claim about who puts it there.

Proving it instead of trusting it

I do not want to take a type’s word for it, so I compiled assertions with an exact-equality check on drizzle-orm 0.45.3 and TypeScript 5.7.2:

ts
type Equal<X, Y> =
  (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false
type Expect<T extends true> = T

type _S = Expect<Equal<typeof users.$inferSelect, {
  id: number
  email: string
  bio: string | null      // present, nullable
  role: string
}>>

type _I = Expect<Equal<typeof users.$inferInsert, {
  email: string           // notNull, no default -> required
  id?: number             // serial -> optional
  bio?: string | null     // nullable -> optional
  role?: string           // notNull + default -> optional
}>>

Both pass with zero errors. That alone proves less than it looks like, though — an Equal helper that is subtly broken passes everything. So I broke one on purpose, claiming bio was optional on select:

plaintext
error TS2344: Type 'false' does not satisfy the constraint 'true'.

Good. The harness has teeth, and “nullable means optional on select” is measurably false.

What that convenience costs

The select type is cheap. The insert type is not, and I only found out because I went looking for the bill.

I generated schemas from 50 to 1,200 columns, compiled each with tsc --extendedDiagnostics, and subtracted a baseline that defines the table without touching either inferred type. The Instantiations counter is TypeScript’s own measure of type-level work.

$inferSelect came out dead linear — the deltas were 1504, 2854, 4204, 5554, which is exactly 27 instantiations per column with no curve at all.

$inferInsert bent upward. Its second differences held near constant (21387, then 21063), which is the signature of a quadratic, and a least-squares fit gave roughly 4.2 · N². In wall-clock terms, at 800 columns the check took 3.89s for insert against 0.69s for select.

Push it far enough and it stops being slow and starts being an error. At 1,000 columns the insert type resolved in 4,765,039 instantiations. At 1,100:

plaintext
error TS2589: Type instantiation is excessively deep and possibly infinite.

TypeScript caps a single expression at 5,000,000 instantiations, and the fit had predicted the wall at 1,041 columns. The measured boundary sits between 1,000 and 1,100. Nobody has a 1,000-column table, so treat that number as a ceiling rather than a warning — the point is the shape of the curve underneath it, which you pay for on every keystroke in your editor.

Two things I measured that I did not expect:

You only pay when something resolves the keys. Declaring function f(v: T) cost 240k instantiations at 500 columns. Asking for keyof T cost 1.32M. Merely having the type around is cheap; forcing TypeScript to enumerate its key set is where the money goes.

Zero required columns is a cliff, not a slope. At 500 columns with five required columns, the insert type cost 1,254,593. With zero required columns it jumped to 5,232,625 — a 4.2× step for removing five columns. That matters because it is an ordinary schema shape: give every column a default or make it nullable, and you have zero required insert keys.

I tried to reproduce that cliff with a hand-written model of the same two-mapped-type pattern and could not — my simplified version cost the same either way. So the cliff lives somewhere in Drizzle’s real conditional types, not in a general rule about TypeScript, and I am not going to claim a mechanism I could not reproduce. There is an open issue tracking the quadratic insert cost against the 0.45.x line.

What to actually do

Name both types and use the right one:

ts
type Post = typeof posts.$inferSelect       // reading
type NewPost = typeof posts.$inferInsert    // writing

A Post is what a query returns and every field is there. A NewPost is what you hand to db.insert(). When a function takes a row it read and passes it somewhere else, it wants Post. Getting this right is free; getting it wrong gives you an id that TypeScript thinks might be undefined, in code that reads rows which always have one.

The shape of this problem is not unique to ORMs. Deriving more than one type from a single definition is exactly what sharing one Zod schema between a form and a handler does, and it has the same sharp edge: one source of truth, several consumers, each needing a slightly different shape of it. The difference here is that both Drizzle types are correct. Only my usage was wrong.

The alternative is writing the row type by hand and keeping it in step with the table yourself, which is the same losing game as letting your structured logs drift out of shape. Inference never drifts, because there is only one definition to drift from. The measurements above are the price of that guarantee, not a reason to skip it.

Check your own schema before you believe any of this. Hover $inferInsert, count the columns without a default, and see whether the type agrees with what you assumed you were storing.

❯ls ./related
❯cat ./comments

Comments are not configured yet. Enable GitHub Discussions and paste the giscus repo-id / category-id into src/consts.ts.