How to use the Alter Table Statement in a SQL Database
Once we have created a table in our database we can use alter statement to modify it.
ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
Syntax :
ALTER TABLE commands we can perform
1-ALTER TABLE Add Column
2-ALTER TABLE Drop Column
3-ALTER TABLE Modify Column
4-ALTER TABLE Rename Column
5-ALTER TABLE Add Index
6-ALTER TABLE Drop Index
7-ALTER TABLE Add Constraint
8-ALTER TABLE Drop Constraint
So let's use our old TEST table script to show some examples of alter table :
Script:
Check the table to see the data and the structure.
Very good
1 -ALTER TABLE Add Column
Syntax:
this is used when we want to add a column to our table .Let's add a column called AGE to our TEST table .
Example:
-so the AGE column should be int .
-and there you go , I have just added a column to our TEST table .
Now check the table :
-it has no values we can see that the column was added .
2- ALTER TABLE Drop Column
using the same table now we will drop the column we have just added (AGE column).
Sintax:
Example:
Nice.Check the table
Very good
See the column AGE is no longer in our table .
3- ALTER TABLE Modify Column
-this is used when we want to change the data type of a column
Sintax:
-so for this example will try alter the column DE from char(20) to char(10).
Example:
-firts we will see the table description do confirm that the column is char(20).
we can see that the column "de" is a char od 20 .
Now let's change the type or the size of the column, make it char of 30 :
Ok, now check the table structure and see the change that we have made
4-ALTER TABLE Rename Column
this command will let use change the name of a column
Sintax:
Note: if you already have data in the table make sure the data types will apply to the data the column has in.
-also the constraints must be applied to the column.
Example:
Now check the table structure:
5-ALTER TABLE Add/Drop Index
-with the Add index statement one can add an index to the table.
Syntax:
Example:
-we will add an index to our table test.
-check the table if we any indexes created .
-we see that the column "id" has no index on it, so we will create one
-check our new index:
To get more info about your index use this command
Sintax:
-this command will bring data about all the indexes found on the table.