Wednesday, December 18, 2024

SQL ALTER TABLE Statement

 The ALTER TABLE statement in SQL is used to modify the structure of an existing table. You can use it to add, modify, or delete columns, or even to add and drop constraints.

Here are some of the common operations you can perform with ALTER TABLE:

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 birthdate DATE;

2. Modify a Column

To change the data type or other properties of an existing column:

ALTER TABLE table_name
MODIFY column_name new_data_type;

Example:

ALTER TABLE employees
MODIFY salary DECIMAL(10, 2);

3. Rename a Column

To rename a column:

ALTER TABLE table_name
RENAME COLUMN old_column_name TO new_column_name;

Example:

ALTER TABLE employees
RENAME COLUMN birthdate TO dob;

4. 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 birthdate;

5. Add a Constraint

To add a new constraint (e.g., a primary key, foreign key, unique constraint):

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);

6. Drop a Constraint

To remove an existing constraint:

ALTER TABLE table_name
DROP CONSTRAINT constraint_name;

Example:

ALTER TABLE employees
DROP CONSTRAINT pk_employee_id;

7. Rename the Table

To rename the entire table:

ALTER TABLE old_table_name
RENAME TO new_table_name;

Example:

ALTER TABLE employees
RENAME TO staff;

These operations allow you to modify the schema of a table in a relational database. The specific syntax and capabilities might vary slightly depending on the database system you are using (e.g., MySQL, PostgreSQL, SQL Server).

No comments:

Post a Comment