ALTER TABLE statement changes the definition of a table.
Required privileges
Refer to the respective subcommands for required privileges.Syntax
Parameters
Change the table only if a table with the current name exists. If one does not exist, do not return an error.
The name of the table you want to change.
Subcommands
Some subcommands can be used in combination in a singleALTER TABLE statement.
ADD COLUMN
Add columns to existing tables. Required privileges: TheCREATE privilege on the table.
Add a column with NOT NULL constraint and DEFAULT value
Add a column with UNIQUE constraint
Add a column with FOREIGN KEY constraint
ADD CONSTRAINT
Add the following constraints to columns:UNIQUECHECKFOREIGN KEY
CREATE privilege on the table.
To add a primary key constraint, you should explicitly define the primary key at table creation. To replace an existing primary key, you can use ADD CONSTRAINT ... PRIMARY KEY.
ALTER COLUMN
UseALTER TABLE ... ALTER COLUMN to:
- Set, change, or drop a column’s
DEFAULTconstraint - Set or drop a column’s
NOT NULLconstraint - Set, change, or drop an
ON UPDATEexpression - Change a column’s data type
- Set the visibility of a column
CREATE privilege on the table.
ALTER PRIMARY KEY
Change the primary key of a table. Required privileges: TheCREATE privilege on the table.
Note: When you change a primary key with ALTER PRIMARY KEY, the old primary key index becomes a UNIQUE secondary index.
DROP COLUMN
Remove columns from a table. Required privileges: TheCREATE privilege on the table.
DROP CONSTRAINT
RemoveCHECK and FOREIGN KEY constraints from columns.
Required privileges: The CREATE privilege on the table.
RENAME COLUMN
Change the name of a column in a table. Required privileges: TheCREATE privilege on the table.
RENAME TO
Change the name of a table. Required privileges: TheDROP privilege on the table and the CREATE privilege on the parent database.
Note: ALTER TABLE ... RENAME TO cannot be used to move a table from one schema or database to another.
VALIDATE CONSTRAINT
Check whether values in a column match a constraint on the column. Required privileges: TheCREATE privilege on the table.
This statement is especially useful after applying a constraint to an existing column via ADD CONSTRAINT.
Examples
Add columns
Add a single column
Add multiple columns
Add constraints
Add the CHECK constraint
Add the FOREIGN KEY constraint with CASCADE
Alter columns
Set the DEFAULT value constraint
Set the NOT NULL constraint
Change a column’s data type
Drop columns
Drop constraints
Rename columns
Rename tables
See also
- CREATE TABLE
- DROP TABLE
- SHOW TABLES
- SHOW COLUMNS