-
Notifications
You must be signed in to change notification settings - Fork 14
07 SQL ‐ Alter Tables
In SQL, the ALTER TABLE
statement is used to modify an existing table's structure, including adding, modifying, or deleting columns, constraints, and indexes. The specific alterations you can perform may vary depending on your database management system. Here's a general overview of how to use ALTER TABLE
:
-
Add a Column: To add a new column to an existing table, you can use the
ADD
clause with theALTER TABLE
statement. For example:ALTER TABLE table_name ADD column_name data_type;
Where
table_name
is the name of the table,column_name
is the name of the new column, anddata_type
is the data type of the new column. -
Modify a Column: You can use the
ALTER TABLE
statement to modify the properties of an existing column. For example, you can change the data type of a column:ALTER TABLE table_name ALTER COLUMN column_name new_data_type;
-
Rename a Column: To rename an existing column, you typically use the
RENAME COLUMN
clause if supported by your database system:ALTER TABLE table_name RENAME COLUMN old_column_name TO new_column_name;
Some database systems may use a different syntax for renaming columns.
-
Drop a Column: To remove an existing column from a table, you can use the
DROP COLUMN
clause:ALTER TABLE table_name DROP COLUMN column_name;
-
Add Constraints: You can use the
ADD CONSTRAINT
clause with theALTER TABLE
statement to add constraints to an existing table. For example, to add a foreign key constraint:ALTER TABLE table_name ADD CONSTRAINT fk_constraint_name FOREIGN KEY (column_name) REFERENCES other_table (other_column);
-
Drop Constraints: To remove a constraint from an existing table, you can use the
DROP CONSTRAINT
clause:ALTER TABLE table_name DROP CONSTRAINT constraint_name;
-
Add or Remove Indexes: You can use
ALTER TABLE
to add or remove indexes on columns as needed. The syntax for this can vary significantly between database systems, so consult your specific database documentation for details.
Remember that the exact syntax and capabilities of the ALTER TABLE
statement may vary depending on the database management system you are using (e.g., MySQL, PostgreSQL, SQL Server). Always refer to your database system's documentation for detailed information on using ALTER TABLE
and any system-specific features or limitations.