How to add new columns to an existing table in SQL
Overview
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:
- Create a new table from scratch. This method can add a new attribute to a new table. First, you have to copy and paste the data from the previous table to the new one and then insert the values of the new attribute. This technique is neither productive nor memory-efficient.
- Use the
ALTERcommand to add a new attribute to an existing table. This command can do this task vigorously and memory-efficiently.
ALTER command
The 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.
Syntax
ALTER TABLE <Table_Name> ADD <Attr1> datatype, <Attr2> datatype...;
Outcome
The following illustration shows the initial schema of the table Student.
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.
Student
Roll_No | Name_Student | Age |
1 | Micheal | NULL |
2 | Marcos | NULL |
Example
-- 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;
Explanation
- In lines 2-6, we create a table named
Studentusing theCREATEcommand. - In lines 8-9, we insert values in the table
Studentby using theINSERTcommand. - In line 11, we display the data of the table
Student. - In line 15, we add a new attribute
Ageusing theALTERcommand. - In line 16, we display the table
Student's data whose schema is updated. By default, all states of the newly added attribute areNULL. We can set default values by using theDEFAULTkeyword just after the attribute’s datatype. - In lines 20-21, we update the values of the
Ageattribute by using theUPDATEcommand. - In line 21, we display the final states of the table
Student.
Free Resources