Day 50 – SQL ALTER Keyword
SQL ALTER keyword is used to modify the structure of an existing table in a database. The most common use of the ALTER keyword is to add, modify, or remove columns from a table. The syntax for using the ALTER keyword to modify a table varies slightly between different SQL implementations, but the basic structure is as follows:
ALTER TABLE table_name
action;
In this syntax, ALTER TABLE
is the SQL statement used to modify an existing table, table_name
is the name of the table being modified, and action
is the specific action being performed on the table.
Some common actions that can be performed using the ALTER keyword include:
- Adding a new column to a table:
ALTER TABLE table_name
ADD column_name data_type;
- Modifying the data type of an existing column:
ALTER TABLE table_name
ALTER COLUMN column_name new_data_type;
- Renaming a column in a table:
ALTER TABLE table_name
RENAME COLUMN old_column_name TO new_column_name;
- Removing a column from a table:
ALTER TABLE table_name
DROP COLUMN column_name;
- Adding a new constraint to a table, such as a primary key or foreign key constraint:
ALTER TABLE table_name
ADD CONSTRAINT constraint_name constraint_type (columns);
In addition to these basic actions, the ALTER keyword can also be used for more advanced table modifications, such as changing the name of a table or adding an index. However, the specific syntax for these types of modifications can vary significantly between different SQL implementations.