The ALTER TABLE keyword in SQL is used to modify an existing table structure. It allows you to add, delete, or modify columns in an existing table, as well as perform other structural changes like renaming a table.
Here are common usages of the ALTER TABLE statement:
1. Add a Column
To add a new column to an existing table:
ALTER TABLE table_name
ADD column_name data_type;
Example:
ALTER TABLE employees
ADD hire_date DATE;
2. Drop a Column
To remove an existing column from a table:
ALTER TABLE table_name
DROP COLUMN column_name;
Example:
ALTER TABLE employees
DROP COLUMN hire_date;
3. Modify a Column
To modify the data type of an existing column or change its properties (like length or default value):
ALTER TABLE table_name
MODIFY column_name new_data_type;
Example:
ALTER TABLE employees
MODIFY salary DECIMAL(10, 2);
4. Rename a Column
To rename an existing column:
ALTER TABLE table_name
RENAME COLUMN old_column_name TO new_column_name;
Example:
ALTER TABLE employees
RENAME COLUMN name TO full_name;
5. Rename a Table
To rename a table:
ALTER TABLE old_table_name
RENAME TO new_table_name;
Example:
ALTER TABLE employees
RENAME TO staff;
6. Add a Constraint
You can add a constraint (like a PRIMARY KEY, FOREIGN KEY, CHECK, or UNIQUE constraint) to a table:
ALTER TABLE table_name
ADD CONSTRAINT constraint_name constraint_type (column_name);
Example:
ALTER TABLE employees
ADD CONSTRAINT pk_employee_id PRIMARY KEY (employee_id);
7. Drop a Constraint
To remove a constraint from a table:
ALTER TABLE table_name
DROP CONSTRAINT constraint_name;
Example:
ALTER TABLE employees
DROP CONSTRAINT pk_employee_id;
The exact syntax for some operations (like modifying columns or renaming constraints) may vary depending on the database system you're using (MySQL, PostgreSQL, SQL Server, etc.).
No comments:
Post a Comment