Skip to main content
Kysely provides a powerful CreateTableBuilder API for defining database tables. Access it through db.schema.createTable().

Basic Table Creation

Create a simple table with columns:

Column Types and Constraints

Common Data Types

Kysely supports standard SQL data types:
For dialect-specific types, use the sql tag:

Column Constraints

The column builder provides these constraint methods:
  • primaryKey() - Mark as primary key
  • notNull() - Disallow NULL values
  • unique() - Ensure uniqueness
  • defaultTo(value) - Set default value
  • unsigned() - Unsigned integers (MySQL)
  • autoIncrement() - Auto-incrementing (MySQL, SQLite)
  • check(expression) - Add check constraint

Auto-Incrementing IDs

Different databases use different approaches: MySQL/SQLite:
PostgreSQL (serial):
PostgreSQL (identity):
MS SQL Server:

Foreign Keys

Column-Level Foreign Keys

Add foreign key constraints directly to columns:

Table-Level Foreign Keys

Some databases (like older MySQL versions) require table-level constraints:

Composite Foreign Keys

Table Constraints

Primary Key Constraints

Define composite primary keys:

Unique Constraints

On PostgreSQL, specify nulls not distinct:

Check Constraints

Generated Columns

Virtual Generated Columns

Stored Generated Columns

Special Table Types

Temporary Tables

On PostgreSQL, control commit behavior:

Conditional Creation

Create Table From SELECT

Advanced Modifiers

Front Modifiers

Add SQL after the create keyword:

End Modifiers

Add SQL to the end of the statement:

Reusable Patterns

Create reusable column definitions: