Introduction
INSERT INTO is a command that is used to store data in tables. The INSERT statement adds a new entry to the table where data can be stored. In this blog, we will see various situations where INSERT INTO would be helpful and how to use this command.
Different ways of inserting data in a relational database
Recommended Topic, sql functions
By SQL INSERT INTO
We can insert data or tuples in the table by using SQL INSERT INTO query command.
There are two different ways which are:
By using attribute/column names
Here we have to mention both the values we want to insert and the column name where we want to insert.
Syntax:
INSERT INTO table_name ( column1,column2,column3…) VALUES(value1,value2,value3…); |
Here
INSERT INTO `table_name` is the command that tells the MySQL server to add a new row into a table named `table_name.`(column_1,column_2,…) specifies the columns to be updated in the new MySQL row VALUES (value_1,value_2,…) specifies the values to be added into the new row
For Example,
Let’s say we have a table for students records as
Roll_No |
Name |
Address |
Adhar_No |
1 |
Amisha |
Ahmedabad |
10100101 |
2 |
Bhavisha |
Pune |
20200202 |
5 |
Akash |
Ahmedabad |
50500505 |
So, to insert a record, we will use the query as:
INSERT INTO STUDENTS(ROLL_NO, NAME, ADDRESS, ADHAR_NO) VALUES(3,Anant,Udaipur,30300303);
INSERT INTO STUDENTS(ROLL_NO,NAME,ADDRESS,ADHAR_NO) VALUES(6,Dun,Ahmedabad,60600606);
INSERT INTO STUDENTS(ROLL_NO,NAME,ADDRESS,ADHAR_NO) VALUES(7,Shivani,Ahmedabad,70700707); |
The final table after running the above queries will be:
Roll_No |
Name |
Address |
Adhar_No |
1 |
Amisha |
Ahmedabad |
10100101 |
2 |
Bhavisha |
Pune |
20200202 |
5 |
Akash |
Ahmedabad |
50500505 |
3 |
Anant |
Udaipur |
30300303 |
6 |
Dun |
Ahmedabad |
60600606 |
7 |
Shivani |
Ahmedabad |
70700707 |
By not mentioning column name
We don’t have to specify the column names where the data will be inserted in this method. We just mention their values.
Syntax:
INSERT INTO table_name VALUES (value1,value2,value3,...); |
HERE
INSERT INTO `table_name` is the command that tells the MySQL server to add a new row into a table named `table_name.`
VALUES (value_1,value_2,…) specifies the values to be added into the new row
For Example,
If we want to insert in the same student’s table, we will use the following query.
INSERT INTO STUDENTS VALUES(4,Harsh,Gandhinagar,40400404); |
The final table after both the queries will be:
Roll_No |
Name |
Address |
Adhar_No |
1 |
Amisha |
Ahmedabad |
10100101 |
2 |
Bhavisha |
Pune |
20200202 |
5 |
Akash |
Ahmedabad |
50500505 |
3 |
Anant |
Udaipur |
30300303 |
6 |
Dun |
Ahmedabad |
60600606 |
7 |
Shivani |
Ahmedabad |
70700707 |
4 |
Harsh |
Gandhinagar |
40400404 |
Also see, SQL EXCEPT