SQL ALTER Statement
The SQL ALTER statement is used to modify existing database objects such as tables and columns.
1. Altering Tables
To modify the structure of an existing table, you can use the ALTER TABLE statement followed by the table name and the desired modifications.
Example:
// Example of adding a new column named "email" to the "employees" table
ALTER TABLE employees
ADD COLUMN email VARCHAR(100);
This example adds a new column named "email" to the "employees" table.
2. Altering Columns
To modify the definition of an existing column in a table, you can use the ALTER TABLE statement followed by the table name and the ALTER COLUMN clause.
Example:
// Example of changing the data type of the "age" column in the "employees" table
ALTER TABLE employees
ALTER COLUMN age INT;
This example changes the data type of the "age" column in the "employees" table to INT.
3. Adding Constraints
To add constraints such as primary keys, foreign keys, or unique constraints to an existing table, you can use the ALTER TABLE statement followed by the table name and the ADD CONSTRAINT clause.
Example:
// Example of adding a primary key constraint to the "employees" table
ALTER TABLE employees
ADD CONSTRAINT pk_employee_id PRIMARY KEY (employee_id);
This example adds a primary key constraint named "pk_employee_id" to the "employees" table.
4. Conclusion
The ALTER statement in SQL is a powerful tool for modifying the structure of existing database objects. Whether it's adding new columns, altering existing columns, or adding constraints, the ALTER statement allows for flexible management of database schemas.
Comments
Post a Comment