📜  ALTER IN SQL (1)

📅  最后修改于: 2023-12-03 15:13:18.250000             🧑  作者: Mango

ALTER IN SQL

ALTER is a command used in SQL to modify an existing database object, such as a table or a view. With ALTER, you can add, modify, or delete columns, constraints, indexes, and many other features.

Syntax

The basic syntax of the ALTER command is as follows:

ALTER keyword object_name clause;

Here, keyword represents what you are modifying, object_name represents the name of the object you are modifying, and clause represents the specific change you want to make.

Common ALTER commands and examples

Here are some common examples of using ALTER in SQL:

1. ALTER TABLE ADD COLUMN

You can use ALTER to add a new column to an existing table. For example, let's say you have a table named employees, and you want to add a column called salary:

ALTER TABLE employees ADD COLUMN salary INT;
2. ALTER TABLE MODIFY COLUMN

You can use ALTER to modify an existing column in a table. For example, let's say you want to change the data type of the salary column from INT to DECIMAL:

ALTER TABLE employees MODIFY COLUMN salary DECIMAL(10,2);
3. ALTER TABLE DROP COLUMN

You can use ALTER to delete an existing column from a table. For example, let's say you want to delete the salary column:

ALTER TABLE employees DROP COLUMN salary;
4. ALTER TABLE ADD CONSTRAINT

You can use ALTER to add a constraint to a table. For example, let's say you have a table named orders, and you want to add a foreign key constraint on the customer_id column to ensure that the customer_id values in the orders table exist in the customers table:

ALTER TABLE orders 
ADD CONSTRAINT fk_customer_id 
FOREIGN KEY (customer_id) 
REFERENCES customers(id);
5. ALTER TABLE DROP CONSTRAINT

You can use ALTER to delete a constraint from a table. For example, let's say you want to delete the foreign key constraint we just added:

ALTER TABLE orders DROP CONSTRAINT fk_customer_id;
Conclusion

The ALTER command in SQL is a powerful tool that allows you to modify existing database objects. Whether you need to add, modify, or delete columns, constraints, or indexes, ALTER gives you the flexibility to make changes to your database schema as needed.