
For an instructor lead, in-depth look at learning SQL click below.
Working with databases is a dynamic task. With the evolution and growth of any application, changes to existing tables and structures become inevitable. In SQL, these modifications can be performed using the ‘ALTER’ statement. This command allows us to add, delete/drop or modify columns in an existing table. It also lets you add and drop various constraints on an existing table.
Using ALTER TABLE
Here’s the basic syntax of the ALTER TABLE command:
1 2 3 4 |
ALTER TABLE table_name ADD column_name datatype; |
Adding Columns
Suppose you have a table named ‘Students’ with columns ‘ID’, ‘Name’, and ‘Age’ and you want to add the column ‘Grade’. Here is how you would do it:
1 2 3 4 |
ALTER TABLE Students ADD Grade varchar(2); |
Dropping Columns
The ALTER TABLE…DROP COLUMN command is used to drop column in a table. It is important to note that column you are about to delete should not be part of any primary key or other constraints. If so, first drop the key and constraints, then delete the column.
Suppose now we want to remove the ‘Grade’ column from the ‘Students’ table:
1 2 3 4 |
ALTER TABLE Students DROP COLUMN Grade; |
Modifying Columns
To change the data type of a column, the ALTER TABLE…MODIFY command is used. However, you should take care when altering column specifications as this may affect existing data.
For example, to modify the ‘Age’ column from integer to varchar in the ‘Students’ table:
1 2 3 4 |
ALTER TABLE Students MODIFY Age varchar(2); |
Adding Constraints
Constraints help us control the kinds of data that can go into a table. We can use ALTER TABLE…ADD CONSTRAINT command to add constraints.
Here’s how you add a new Primary Key:
1 2 3 4 |
ALTER TABLE Students ADD CONSTRAINT PK_Students PRIMARY KEY (ID); |
Conclusion
The ALTER TABLE statement in SQL is a potent tool, allowing complete control over our existing database structures. We can add new columns, change existing ones and even add or remove constraints. Before altering anything in your database, be sure to have a good understanding of what outcome each action will lead to and always test on a non-production environment first to avoid any catastrophic mistakes.