Tables are the building blocks in any Database. Each table consists of two components: tuples and attributes represent rows and columns respectively. We know that the name of attributes, their data types, and their key values are declared at the time of creation. We create attributes in the table as per our need, but the probability is very high to append new attributes in the future. There are two ways to add new attributes to the table:
ALTER
command to add a new attribute to an existing table. This command can do this task vigorously and memory-efficiently.ALTER
commandThe ALTER
command is frequently used to delete, modify and add columns in an existing table. The ALTER
command can also be used to add and drop constraints on a table.
ALTER TABLE <Table_Name> ADD <Attr1> datatype, <Attr2> datatype...;
The following illustration shows the initial schema of the table Student
.
Roll_No | Name_Student |
1 | Micheal |
2 | Marcos |
The following illustration shows the schema of the Student
table after appending the Age
attribute using the ALTER
command.
Roll_No | Name_Student | Age |
1 | Micheal | NULL |
2 | Marcos | NULL |
-- Create a tableCREATE TABLE Student(Roll_No int primary key,Name_Student varchar(15));-- Insert valuesINSERT INTO Student VALUES(1, "Micheal");INSERT INTO Student VALUES(2, "Marcos");-- Print DataSELECT Roll_No AS ID, Name_Student AS Name FROM Student;SELECT "";-- Add Another columns in the same tableALTER TABLE Student ADD Age int;SELECT Roll_No AS ID, Name_Student AS Name, Age FROM Student;SELECT "";-- Update valuesUPDATE Student SET Age=19 WHERE Roll_No=1;UPDATE Student SET Age=17 WHERE Roll_No=2;SELECT Roll_No AS ID, Name_Student AS Name, Age FROM Student;
Student
using the CREATE
command.Student
by using the INSERT
command.Student
.Age
using the ALTER
command.Student
's data whose schema is updated. By default, all states of the newly added attribute are NULL
. We can set default values by using the DEFAULT
keyword just after the attribute’s datatype.Age
attribute by using the UPDATE
command.Student
.