SQL ALTER
Complete Details
The ALTER statement in SQL is used to modify the structure of a database object, such as a table, index, or view. It can be used to add, modify, or remove columns, change data types, add or remove constraints, and rename objects.
Here are some of the most common ALTER operations:
1. Adding
a new column:
ALTER TABLE table_name ADD
new_column_name data_type;
For example, to add a new
column called phone_number to the customers table, you would use the following
query:
ALTER TABLE emp ADD
phone_number VARCHAR(20);
2. Modifying
an existing column:
ALTER TABLE table_name ALTER column_name data_type;
For example, to change the data type of the email column in the customers table from VARCHAR(50) to VARCHAR(100), you would use the following query:
ALTER TABLE customers
ALTER email VARCHAR(100);
3. Adding
a constraint:
ALTER TABLE table_name ADD
CONSTRAINT constraint_name constraint_type;
ALTER TABLE customers ADD
CONSTRAINT pk_customers PRIMARY KEY (id);
4. Removing
a constraint:
ALTER TABLE table_name DROP CONSTRAINT constraint_name;
For example, to remove the primary key constraint from the id column in the customers table, you would use the following query
ALTER TABLE customers DROP
CONSTRAINT pk_customers;
5. Renaming
an object:
ALTER TABLE table_name RENAME TO new_table_name;
For example, to rename the customers table to customer_details, you would use the following query:
6. Dropping a column:
ALTER TABLE table_name DROP COLUMN column_name;
7. ALTER
VIEW:
- Modifying a view's definition: ALTER VIEW
view_name AS new_view_definition;
8. ALTER
PROCEDURE:
- Modifying a stored procedure's definition:
ALTER PROCEDURE procedure_name new_procedure_definition;
9. ALTER
INDEX:
- Modifying an index's definition or
properties: ALTER INDEX index_name ON table_name [options];
10. ALTER
DATABASE:
- Modifying database options, such as
collation or recovery model: ALTER DATABASE database_name [options];
· What is the difference between the ALTER TABLE and CREATE TABLE statements?
Answer: The ALTER TABLE statement is used to modify the structure of an existing table, while the CREATE TABLE statement is used to create a new table.
·
How do you add a new column to a table that
already contains data?
Answer:
When you change the data type of an existing column, the data in the column may
be converted to the new data type. If the new data type is smaller than the old
data type, some of the data may be lost.
Answer: When you add a constraint to a table, the constraint will be enforced on all future data that is inserted into the table. Existing data will not be checked for compliance with the constraint until it is updated.
·
How
do you remove a constraint from a table?
0 Comments
Thanks for your message.