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:Dropping Columns
Renaming Columns
Modifying Columns
Using alterColumn
Change column properties (PostgreSQL, SQLite):Using modifyColumn
For MySQL and Oracle, usemodifyColumn instead:
Constraint Operations
Adding Constraints
Primary Key Constraints
Unique Constraints
nulls not distinct:
Foreign Key Constraints
Check Constraints
Dropping Constraints
Drop any constraint by name:Renaming Constraints
Index Operations
Adding Indexes
Dropping Indexes
Chaining Multiple Alterations
Some operations can be chained in a single statement:Database-Specific Considerations
PostgreSQL
- Supports
alterColumnfor modifying column properties - Allows
IF NOT EXISTSon add column operations - Supports
nulls not distincton unique constraints
MySQL
- Use
modifyColumninstead ofalterColumn - Supports
FIRSTandAFTERfor column positioning (use with modifiers)
SQLite
SQLite has limitedALTER TABLE support:
- Can add columns
- Can rename tables and columns
- Cannot drop columns (in older versions)
- Cannot modify column types directly
- Create a new table with the desired schema
- Copy data from the old table
- Drop the old table
- Rename the new table