ALTER TABLE changes the structure of a table that already exists, while keeping its data. It adds, renames and removes columns, changes a column’s type, and adds or removes constraints.
The examples change the Productions table from the example database.
Adding a column
Section titled “Adding a column”The company now wants to record when each production is released:
ALTER TABLE ProductionsADD ReleaseDate date;Every existing row gets the new column, empty until a value is set:
| ProductionID | Title | ReleaseDate |
|---|---|---|
| 1 | The Lantern Keepers | |
| 2 | Quarry Lane | |
| 3 | Saltmarsh | |
| 4 | Six Bells | |
| 5 | Fennick’s Return |
Renaming a column
Section titled “Renaming a column”ALTER TABLE ProductionsRENAME COLUMN ReleaseDate TO PremiereDate;PostgreSQL, MySQL 8, Oracle and SQLite accept this form. SQL Server renames with a built-in procedure instead: EXEC sp_rename 'Productions.ReleaseDate', 'PremiereDate', 'COLUMN';.
Dropping a column
Section titled “Dropping a column”ALTER TABLE ProductionsDROP COLUMN PremiereDate;The column and every value in it are gone.
Changing a column’s type
Section titled “Changing a column’s type”This is where databases differ most. To let Format hold up to 100 characters:
| Database | Statement |
|---|---|
| SQL Server, Access | ALTER TABLE Productions ALTER COLUMN Format varchar(100); |
| PostgreSQL | ALTER TABLE Productions ALTER COLUMN Format TYPE varchar(100); |
| MySQL | ALTER TABLE Productions MODIFY COLUMN Format varchar(100); |
| Oracle | ALTER TABLE Productions MODIFY Format varchar2(100); |
SQLite cannot change a column’s type; the usual way round is to create a new table with the right types, copy the data across, and swap the two.