Most TypeScript developers either write raw SQL strings (losing type safety) or use heavy ORMs that abstract away the database entirely. Kysely offers the perfect middle ground: a type-safe SQL query builder that gives you full control.
What Is Kysely?
Kysely is a type-safe TypeScript SQL query builder. No magic, no code generation at runtime — just pure TypeScript types that ensure your queries are correct at compile time.
Quick Start
npm install kysely
import { Kysely, PostgresDialect } from 'kysely'
import { Pool } from 'pg'
interface Database {
person: {
id: number
first_name: string
last_name: string
email: string
}
}
const db = new Kysely<Database>({
dialect: new PostgresDialect({
pool: new Pool({ connectionString: process.env.DATABASE_URL })
})
})
// Fully type-safe — TypeScript catches errors at compile time
const users = await db
.selectFrom('person')
.select(['id', 'first_name', 'email'])
.where('email', 'like', '%@gmail.com')
.orderBy('first_name')
.execute()
Why Developers Choose Kysely Over ORMs
| Feature | Kysely | Traditional ORMs |
|---|---|---|
| Type safety | Compile-time SQL validation | Runtime errors |
| Learning curve | Know SQL = know Kysely | Learn ORM-specific API |
| Query control | Full SQL power | Limited by abstraction |
| Bundle size | ~30KB | 200KB-1MB+ |
| Migrations | Built-in, type-safe | Framework-specific |
Real-World Use Case
A fintech startup switched from Prisma to Kysely when they needed complex window functions and CTEs that ORMs couldn't express naturally:
const monthlyRevenue = await db
.selectFrom('transactions')
.select([
'customer_id',
sql<number>`sum(amount)`.as('total'),
sql<number>`row_number() over (order by sum(amount) desc)`.as('rank')
])
.where('created_at', '>=', startOfMonth)
.groupBy('customer_id')
.execute()
Result: 40% faster queries and zero runtime type errors in production.
Supported Databases
- PostgreSQL
- MySQL
- SQLite
- MSSQL (community plugin)
Key Features
- Zero runtime overhead — types exist only at compile time
- Built-in migrations — type-safe schema changes
- Plugin system — camelCase, logging, and more
-
Raw SQL escape hatch — use
sqltemplate tag when needed
Get Started
- Documentation
- GitHub — 12K+ stars
- Playground — try it in the browser
Need to extract data from websites into your database? Check out my web scraping tools on Apify — get clean, structured data ready for your Kysely queries. Questions? Email me at spinov001@gmail.com
Top comments (0)