How to use Kysely with TypeScript and PostgreSQL
By Flavio
Tagged: Database
Build a small PostgreSQL-backed store with Kysely, from the first typed query to joins, transactions, migrations, debugging, and tests.
I like SQL because I can see the exact tables, columns, and conditions that decide which rows come back. I also like TypeScript: when I rename a column or mistype a table name, I want my editor to catch it before anything reaches production, and I want missing rows reflected in the return type.
Kysely bridges those two worlds. It’s a type-safe SQL query builder for TypeScript that keeps the database visible through an API that still looks and feels like SQL.
In this tutorial we’ll build a small store that sells software products, with users, products, and orders. We’ll start with a single select query, then work our way through filters, joins, inserts, updates, a transaction, migrations, and tests.
The store we are building
Our store needs three tables:
userscontains sellers and customersproductscontains the products for saleordersconnects a customer to a product
Here’s how those tables relate to each other:
You could write every query as a plain SQL string, and it would work, except TypeScript wouldn’t know anything about what’s inside those strings. It wouldn’t know that products.price_in_cents is a number or that an order status can only be pending, paid, or cancelled. A full ORM goes in the opposite direction, wrapping your queries in models and relations that hide parts of the SQL. Kysely sits right in the middle.
With Kysely, you write a query like this:
const product = await db
.selectFrom('products')
.select(['id', 'name', 'price_in_cents'])
.where('id', '=', productId)
.executeTakeFirst()
Kysely compiles that to parameterized PostgreSQL:
select "id", "name", "price_in_cents"
from "products"
where "id" = $1
Notice that productId gets passed separately as a query parameter instead of being interpolated into the SQL string. TypeScript also infers the return type automatically:
{
id: number
name: string
price_in_cents: number
} | undefined
That undefined in the type matters because a product with that ID might not exist, so TypeScript makes sure you handle the missing case right away.
Install Kysely
We’ll use PostgreSQL and its standard Node.js driver, pg:
npm install kysely pg
npm install --save-dev @types/pg
Kysely expects TypeScript strict mode, so make sure it’s enabled in tsconfig.json:
{
"compilerOptions": {
"strict": true
}
}
Kysely also ships with built-in dialects for MySQL, Microsoft SQL Server, SQLite, and PGlite, and community dialects cover other databases and runtimes. A dialect compiles queries for a specific SQL flavor and talks to a compatible database driver. We’ll stick with PostgreSQL here so we can focus on Kysely itself.
Tell TypeScript what is in the database
Kysely doesn’t inspect the database every time you write a query. Instead, you give it a TypeScript interface describing your schema:
import type {
ColumnType,
Generated,
Insertable,
Selectable,
Updateable,
} from 'kysely'
interface UserTable {
id: Generated<number>
email: string
name: string
created_at: ColumnType<Date, string | undefined, never>
}
interface ProductTable {
id: Generated<number>
created_by: number
name: string
price_in_cents: number
}
interface OrderTable {
id: Generated<number>
user_id: number
product_id: number
quantity: number
status: 'pending' | 'paid' | 'cancelled'
created_at: ColumnType<Date, string | undefined, never>
}
export interface Database {
users: UserTable
products: ProductTable
orders: OrderTable
}
export type User = Selectable<UserTable>
export type NewUser = Insertable<UserTable>
export type UserUpdate = Updateable<UserTable>
The keys in Database are the actual table names, and each table interface lists its columns. Generated<number> tells Kysely that PostgreSQL generates the ID, so the field is present when you select a row, but you don’t have to pass it on insert.
ColumnType<Date, string | undefined, never> gives created_at a different type for each operation:
- A select returns a
Date. - An insert can pass a string or omit the value.
- An update can’t change it.
Also notice that a nullable column uses string | null instead of an optional property, since null is a real value the database can return whereas an optional property might not exist at all. Keep in mind that this interface only describes the database for TypeScript; it doesn’t create tables, validate incoming input, or convert runtime values. We’ll come back to those boundaries later.
Connect to PostgreSQL
Next, create the Kysely instance:
import { Kysely, PostgresDialect } from 'kysely'
import { Pool } from 'pg'
import type { Database } from './database-types'
const dialect = new PostgresDialect({
pool: new Pool({
connectionString: process.env.DATABASE_URL,
max: 10,
}),
})
export const db = new Kysely<Database>({ dialect })
Create one instance for your database and reuse it across the app. The PostgreSQL dialect manages a connection pool under the hood, so putting this setup inside a request handler will recreate the pool on every request and quickly open too many connections.
In a short-lived script, close the instance when you’re done so the process can exit:
await db.destroy()
If you deploy to serverless or edge runtimes like Cloudflare Workers, use a driver built for that environment instead of a traditional TCP pool.
Make the first query
Let’s insert our first user:
const user = await db
.insertInto('users')
.values({
email: '[email protected]',
name: 'Flavio',
})
.returning(['id', 'email'])
.executeTakeFirstOrThrow()
Even on this first query, TypeScript already helps out. You don’t need to provide id because it’s generated, and you can skip created_at because its insert type allows undefined, while dropping email triggers a compile error before the query ever runs. PostgreSQL doesn’t return the inserted row by default, so returning() tells it to send back just the fields we need.
Now let’s read that user back:
const user = await db
.selectFrom('users')
.select(['id', 'name', 'email'])
.where('email', '=', '[email protected]')
.executeTakeFirst()
Use executeTakeFirst() when getting no match is a normal case, since it returns the first row or undefined. When the row has to exist, use executeTakeFirstOrThrow(), which throws if the product is missing:
const product = await db
.selectFrom('products')
.selectAll()
.where('id', '=', productId)
.executeTakeFirstOrThrow()
When you want multiple rows, call execute() to get an array:
const products = await db
.selectFrom('products')
.select(['id', 'name', 'price_in_cents'])
.execute()
My advice is to select specific columns at application boundaries instead of selecting everything. That way, a private column you add to the table later won’t accidentally leak into an API response.
Look at the SQL
Query builders don’t execute anything until you call an execution method, which means you can compile a query and inspect it without hitting PostgreSQL at all:
const query = db
.selectFrom('products')
.select(['id', 'name'])
.where('price_in_cents', '>=', 2900)
const compiled = query.compile()
console.log(compiled.sql)
console.log(compiled.parameters)
The compiled object gives you the exact SQL string and parameter array Kysely will send:
{
sql: 'select "id", "name" from "products" where "price_in_cents" >= $1',
parameters: [2900]
}
Being able to see the generated SQL directly is one of my favorite things about Kysely whenever I want to double-check a query.
Add products and filters
Let’s add two products to the store:
await db
.insertInto('products')
.values([
{
created_by: user.id,
name: 'Page Saver',
price_in_cents: 2900,
},
{
created_by: user.id,
name: 'Events Logger',
price_in_cents: 3900,
},
])
.execute()
Now suppose the products endpoint accepts two optional filters: a seller ID and a minimum price. Kysely query builders are immutable, so each method call returns a new builder and you reassign it as you apply each filter:
let query = db
.selectFrom('products')
.select(['id', 'name', 'price_in_cents'])
if (sellerId !== undefined) {
query = query.where('created_by', '=', sellerId)
}
if (minimumPrice !== undefined) {
query = query.where('price_in_cents', '>=', minimumPrice)
}
const products = await query.execute()
I used this exact pattern in a Hono marketplace API where the endpoint returned every product by default and narrowed the query whenever the URL included a seller filter.
Watch out for that reassignment, because calling a filter method on its own doesn’t mutate the original builder:
query.where('created_by', '=', sellerId)
You have to keep the returned builder:
query = query.where('created_by', '=', sellerId)
Join the store together
Say a customer places an order and we want to display the order along with the product name. In SQL that’s a join, and Kysely keeps the same structure:
const orders = await db
.selectFrom('orders')
.innerJoin('products', 'products.id', 'orders.product_id')
.select([
'orders.id',
'orders.quantity',
'orders.status',
'products.name as product_name',
])
.where('orders.user_id', '=', userId)
.execute()
Once products is joined, Kysely makes its columns available and picks up the alias so every returned row has a product_name property. The compiled SQL looks just like what you’d write by hand:
select
"orders"."id",
"orders"."quantity",
"orders"."status",
"products"."name" as "product_name"
from "orders"
inner join "products"
on "products"."id" = "orders"."product_id"
where "orders"."user_id" = $1
If the related row is optional, use a left join and Kysely will automatically include null in the types of columns from the optional table. If joins still feel a bit fuzzy, check out my SQL joins guide first, since Kysely adds types on top of standard SQL join behavior.
Place an order safely
Placing an order takes more than one step: we need to look up the product and then create the order as a single unit of work. Wrap both statements in a transaction:
const order = await db
.transaction()
.execute(async (trx) => {
const product = await trx
.selectFrom('products')
.select(['id', 'price_in_cents'])
.where('id', '=', productId)
.executeTakeFirstOrThrow()
return trx
.insertInto('orders')
.values({
user_id: userId,
product_id: product.id,
quantity: 1,
status: 'pending',
})
.returningAll()
.executeTakeFirstOrThrow()
})
When the callback finishes, Kysely commits the transaction. If it throws, Kysely rolls it back. Always run queries through the trx object inside the callback, because anything called on the outer db instance runs outside the transaction.
I used the same pattern in an Astro password-reset flow, selecting a reset token and deleting it before returning the user ID:
const token = await db
.transaction()
.execute(async (trx) => {
const storedToken = await trx
.selectFrom('password_reset_token')
.selectAll()
.where('id', '=', tokenId)
.executeTakeFirstOrThrow()
await trx
.deleteFrom('password_reset_token')
.where('id', '=', tokenId)
.execute()
return storedToken
})
Your application code still defines what counts as a valid token, while Kysely keeps the database steps explicit and typed. If you need strict one-time behavior under concurrent requests, pair this with row locking or a single atomic delete with returning(), since a transaction groups statements together while the database’s isolation level controls concurrency.
Update and delete data
Once payment succeeds, we can update the order status:
const paidOrder = await db
.updateTable('orders')
.set({ status: 'paid' })
.where('id', '=', order.id)
.returning(['id', 'status'])
.executeTakeFirstOrThrow()
You can also compute a new value directly from the column’s current value, incrementing the quantity in PostgreSQL without reading it into JavaScript first:
await db
.updateTable('orders')
.set((eb) => ({
quantity: eb('quantity', '+', 1),
}))
.where('id', '=', order.id)
.execute()
And here’s how to remove a cancelled order:
const deleted = await db
.deleteFrom('orders')
.where('id', '=', order.id)
.returning('id')
.executeTakeFirst()
Be careful with updates and deletes, because Kysely doesn’t add any safety net for you. Leaving off where() is still valid, well-typed SQL, and it will update or wipe every row in the table.
Aggregate data
Beyond basic CRUD, you’ll eventually need aggregates, like counting how many paid orders each user placed:
const totals = await db
.selectFrom('orders')
.select((eb) => [
'user_id',
eb.fn.count<number>('id').as('order_count'),
])
.where('status', '=', 'paid')
.groupBy('user_id')
.execute()
For larger queries, you can use a common table expression to break the steps apart:
const result = await db
.with('paid_orders', (db) =>
db
.selectFrom('orders')
.select(['user_id', 'product_id'])
.where('status', '=', 'paid'),
)
.selectFrom('paid_orders')
.innerJoin(
'products',
'products.id',
'paid_orders.product_id',
)
.select(['paid_orders.user_id', 'products.name'])
.execute()
Both the CTE name and the columns it selects are typed just like regular tables.
No query builder covers every feature of every database, so whenever the builder gets in the way you can drop down to Kysely’s sql template tag:
import { sql } from 'kysely'
const email = '[email protected]'
const result = await sql<{ id: number }>`
select id from users where email = ${email}
`.execute(db)
Values interpolated into the sql tag still become safe query parameters. Dynamic table and column names are a different story because they’re SQL identifiers rather than values: if you use an escape hatch like sql.ref(), validate the identifier against an allowlist yourself instead of passing raw user input. Reach for raw SQL when it makes a query clearer or lets you use a database-specific feature, just avoid rebuilding unsafe string concatenation.
Keep the types aligned with the database
We wrote the Database interface by hand above so the mapping to SQL was easy to follow. In a production app, I’d rather let the database stay the source of truth, so I used kysely-codegen in both of my Kysely projects:
npx kysely-codegen
Then the application imports the generated type:
import type { DB } from 'kysely-codegen'
export const db = new Kysely<DB>({ dialect })
Keep the order of steps consistent in your workflow:
Run the migration first, regenerate the types second, and type-check the app last. If the generated file and the database ever disagree, fix the migration or generation step instead of editing the generated file by hand, which only hides the drift until the next run.
Change the schema with migrations
As the store grows, your schema will change too, like adding a description column to products. Kysely includes schema and migration primitives where each migration exports an up function to apply the change and a down function to reverse it:
import { Kysely } from 'kysely'
export async function up(db: Kysely<any>) {
await db.schema
.alterTable('products')
.addColumn('description', 'text')
.execute()
}
export async function down(db: Kysely<any>) {
await db.schema
.alterTable('products')
.dropColumn('description')
.execute()
}
Notice Kysely<any> in the signature, which the official migration guide uses on purpose. A migration reflects the schema at one point in time, while your application’s Database type reflects the schema today, so old migrations need to keep compiling even after later schema changes. Keep migrations self-contained and don’t import current application helpers into them.
To load and run migration files, you can wire up Kysely’s Migrator, or install kysely-ctl if you’d rather have a ready-made CLI runner.
Debug a surprising query
Kysely can generate completely valid SQL that still runs slowly. When a query behaves unexpectedly, I debug it straight down to PostgreSQL:
- Call
.compile()and inspect the SQL and parameters. - Run
EXPLAINorEXPLAIN ANALYZEin PostgreSQL. - Check indexes and row counts.
- Verify the driver returns the runtime types in the interface.
- Reduce the query until the unexpected part stands out.
You can also turn on query logging on the Kysely instance:
export const db = new Kysely<Database>({
dialect,
log: ['query', 'error'],
})
Just make sure you don’t log sensitive parameters in production, since queries often include emails, password-reset tokens, or private user data. Query plans, indexes, locks, and table statistics are still PostgreSQL’s job, and because Kysely keeps the underlying SQL close to the surface, they’re straightforward to track down.
Test the queries at two levels
For conditional query-building code, you can test the compiled SQL without opening a database connection:
const query = db
.selectFrom('products')
.select(['id', 'name'])
.where('price_in_cents', '>=', 2900)
const compiled = query.compile()
expect(compiled.sql).toContain('price_in_cents')
expect(compiled.parameters).toEqual([2900])
That kind of test is fast, though it only verifies query construction. An integration test against a temporary PostgreSQL database catches a different class of problems:
- a migration and the generated types disagree
- a constraint behaves differently than expected
- the driver returns a surprising runtime value
- transaction isolation matters
- a query works in one dialect but not another
For important database code, a small real database is worth a lot more than a big mock.
What Kysely does not do
Once you’ve built the store, Kysely’s boundaries are pretty clear. It isn’t a full ORM, so it doesn’t give you model instances, lazy-loaded relations, an identity map, or a unit-of-work abstraction. You pick the joins and write the queries yourself.
It isn’t a runtime validator either. TypeScript disappears at runtime, so if an API request comes in with an invalid email, Kysely won’t reject it for you. I validate untrusted input with a library like Zod before building the query.
Kysely also trusts whatever runtime types you declare. If pg returns a PostgreSQL bigint as a string while your interface says number, you’ll still get a string at runtime. The same thing applies to numeric, JSON, and timestamp columns.
The complete flow looks like this:
Kysely owns the typed query, while runtime validation, application rules, the driver, and PostgreSQL stay separate parts of the app.
How I would use Kysely now
If you’re building a TypeScript service on top of an existing PostgreSQL database, Kysely is a great fit. Keep your migrations as the schema history, generate the database interface with kysely-codegen, validate API input with Zod, and put reusable queries into small functions like this one:
export async function findPaidOrders(userId: number) {
return db
.selectFrom('orders')
.innerJoin('products', 'products.id', 'orders.product_id')
.select([
'orders.id',
'orders.quantity',
'products.name as product_name',
])
.where('orders.user_id', '=', userId)
.where('orders.status', '=', 'paid')
.execute()
}
That function has one job and returns the exact shape its caller needs.
This is close to how I used Kysely in my Hono marketplace API, where Hono handled HTTP and Kysely handled direct queries with optional filters and joins. I also used it in an Astro authentication flow where transactions mattered a lot more than basic CRUD. In both projects, the endpoints mapped closely to SQL operations, and I wanted full control over every selected column and join.
It also works well when several TypeScript services share an existing database. Generating types straight from the real schema cuts down on handwritten models drifting out of sync.
When I would choose something else
Don’t pick Kysely to avoid learning SQL. Because the API mirrors SQL so closely, you still need to understand joins, nulls, constraints, indexes, transactions, and query plans. Kysely makes SQL safer to write in TypeScript, though it won’t replace knowing how your database works.
Other tools make more sense in a few common situations:
- Pick Drizzle if you want TypeScript schema declarations, relations, and a broader toolkit built around the schema.
- Go with a higher-level ORM if your team wants model-oriented relation loading and is happy to live with that abstraction.
- Stick to raw SQL if a service only has a handful of stable, complex queries where TypeScript query composition doesn’t add much.
Kysely is also a poor fit outside TypeScript, since most of its value lives in the type system. And if you’re targeting Cloudflare D1, check whether the community dialect fits your project first. D1 still comes with SQLite behavior and Worker runtime constraints, and no query builder can smooth away every difference between databases.
Large query types can also push TypeScript pretty hard. Kysely provides $assertType() for deliberate boundaries where you want to swap a deeply nested inferred type for a simpler, structurally equal one. Use it to simplify a type you know is right, rather than to hide a mismatch.
Why I like Kysely
I like Kysely because it doesn’t try to hide the database from you. Tables, joins, and transactions stay right in view, so when a query is slow you can inspect the SQL and ask PostgreSQL for its query plan, while TypeScript still catches missing columns, invalid inserts, and mismatched return shapes.
If you want to try it, start small: define one database interface, write a single select query, compile it, and inspect the generated SQL. You can bring in joins, transactions, generated types, and migrations once your app needs them.
Want me to talk about your product? You can sponsor this site.
Related posts about database: