Wednesday, December 18, 2024

SQL ALTER Keyword

 The ALTER keyword in SQL is used to modify the structure of an existing database object, such as a table. It allows you to add, delete, or modify columns in a table, as well as to modify other attributes of database objects like indexes, constraints, or keys.

Here are the most common uses of the ALTER keyword:

1. Add a Column

To add a new column to an existing table:

ALTER TABLE table_name
ADD column_name datatype;

Example:

ALTER TABLE employees
ADD age INT;

2. Modify a Column

To modify an existing column (e.g., change its datatype or size):

ALTER TABLE table_name
MODIFY COLUMN column_name new_datatype;

Example:

ALTER TABLE employees
MODIFY COLUMN age VARCHAR(3);

(Note: The syntax may vary slightly depending on the SQL database you're using, like MySQL or SQL Server.)

3. Drop a Column

To delete an existing column from a table:

ALTER TABLE table_name
DROP COLUMN column_name;

Example:

ALTER TABLE employees
DROP COLUMN age;

4. Rename a Column (in some SQL databases)

In some databases, such as MySQL, you can rename a column using:

ALTER TABLE table_name
CHANGE old_column_name new_column_name datatype;

Example:

ALTER TABLE employees
CHANGE age employee_age INT;

5. Add a Constraint

To add a constraint (like a foreign key or a unique constraint) to a table:

ALTER TABLE table_name
ADD CONSTRAINT constraint_name constraint_type;

Example:

ALTER TABLE employees
ADD CONSTRAINT fk_department FOREIGN KEY (department_id) REFERENCES departments(department_id);

6. Drop a Constraint

To drop an existing constraint:

ALTER TABLE table_name
DROP CONSTRAINT constraint_name;

Example:

ALTER TABLE employees
DROP CONSTRAINT fk_department;

7. Rename a Table

To rename an entire table:

ALTER TABLE old_table_name
RENAME TO new_table_name;

Example:

ALTER TABLE employees
RENAME TO staff;

The exact syntax may vary depending on the SQL database you're using (e.g., MySQL, PostgreSQL, SQL Server), but the general concept remains the same.

No comments:

Post a Comment