SQL INSERT is used to insert single or multiple records into a table.

The data can be inserted in two ways

A. By using SQL INSERT INTO statement.

B. By using SQL INSERT INTO SELECT statement.

 

1. By using SQL INSERT INTO

You can insert the data into the table directly by using SQL INSERT INTO and it can be done in two ways.

You can specify the column names or ignore them while inserting data.

To insert partial column values, you must have to specify the column names. To insert all column values, you can either specify or ignore the column names

 

The syntax of INSERT INTO command is as follows:

If you specify the column names, syntax is

INSERT INTOTable_name

(column1, column2, column3,….)

VALUES (value1, value2, value3,…);

 

If you ignore the column names, syntax is as follows:

INSERT INTOTable_name

VALUES (value1, value2, value3 …);

 

Note: At the time of inserting all column values you need not specify the column names but the values must be entered in the order which the columns exist.

Example:

In the previous example how to create a table we created a table. If we want to insert data into the table then it can be done as:

INSERT INTO Student ( StudentID, Student_name, Address, City)

VALUES ( 1, Nithin, Bank Street, Hyderabad );

 

And the table will look like this:

 

StudentIDStudent_NameAddressCity
1NithinBank streetHyderabad

 

And if you ignore using column names then the example can be given as:

INSERT INTO Student

VALUES (2, Bharath, Panama Street, California)

 

Now the table looks like this

 

StudentIDStudent_NameAddressCity
1NithinBank streetHyderabad
2BharathPanama StreetCalifornia

 

2. INSERT INTO SELECT

This statement is used to insert multiple records into a table. It selects data from one table and inserts the data into other existing table.

The syntax for SQL INSERT INTO SELECT is

INSERT INTO table1

SELECT * FROM table2;

 

This is to copy all columns from table2 to table 1. But if you want to insert only specified columns then

INSERT INTO table1 (column1, column2)

SELECT column1,column2 FROM table2;