Kysely’s AlterTableBuilder allows you to modify existing database tables. Access it through db.schema.alterTable().
Renaming Tables
Rename a table:
Moving to Different Schema
On databases that support schemas (PostgreSQL, MSSQL):
Column Operations
Adding Columns
Add new columns with constraints:
Multiple columns in one statement:
Dropping Columns
Drop multiple columns:
Renaming Columns
Modifying Columns
Using alterColumn
Change column properties (PostgreSQL, SQLite):
The alterColumn method only allows one alteration per call. To make multiple changes, execute separate statements.
Using modifyColumn
For MySQL and Oracle, use modifyColumn instead:
Constraint Operations
Adding Constraints
Primary Key Constraints
Unique Constraints
On PostgreSQL, use nulls not distinct:
Foreign Key Constraints
Composite foreign keys:
Check Constraints
Dropping Constraints
Drop any constraint by name:
On some databases, specify the constraint type:
Renaming Constraints
Index Operations
Adding Indexes
Unique indexes:
Multi-column indexes:
Dropping Indexes
Chaining Multiple Alterations
Some operations can be chained in a single statement:
Not all databases support multiple alterations in one statement. If you encounter errors, split them into separate alterTable calls.
Database-Specific Considerations
PostgreSQL
- Supports
alterColumn for modifying column properties
- Allows
IF NOT EXISTS on add column operations
- Supports
nulls not distinct on unique constraints
MySQL
- Use
modifyColumn instead of alterColumn
- Supports
FIRST and AFTER for column positioning (use with modifiers)
SQLite
SQLite has limited ALTER TABLE support:
- Can add columns
- Can rename tables and columns
- Cannot drop columns (in older versions)
- Cannot modify column types directly
For unsupported operations, you’ll need to:
- Create a new table with the desired schema
- Copy data from the old table
- Drop the old table
- Rename the new table
Reusable Patterns
Create reusable alteration functions: