Chapter 7: SQL Insert

SQL INSERT STATEMENT

The INSERT INTO command is used to insert new rows in a table.SQL INSERT statement or query is used to insert a single or a multiple records in a table.

There are two ways to insert data in a table:

1) Inserting data directly into a table

You can insert a row in the table by using SQL INSERT INTO command. But there are 2 ways to do this.

  1. By specifying column names
  2. Without specifying column names

1.If you specify the column names, syntax of the insert into statement will be as follows:

INSERT INTO TABLE_NAME  
[(col1, col2, col3,.... col N)]  
VALUES (value1, value2, value 3, .... Value N);  

Note:Here col1, col2, col3, …. colN are the columns of the table in which you want to insert data.

2.But, If you ignore the column names, syntax of the insert into statement will be as follows:

INSERT INTO TABLE_NAME  
VALUES (value1, value2, value 3, .... Value N);  

2) Inserting data through SELECT Statement

SQL INSERT INTO SELECT Syntax:

INSERT INTO table_name  
[(column1, column2, .... column)]  
SELECT column1, column2, .... Column N  
FROM table_name [WHERE condition];  

Note: when you add a new row, you should make sure that data type of the value and the column should be matched.

If any integrity constraints are defined for the table, you must follow them.

SQL INSERT INTO SELECT

We know how to insert a single row or an individual data in a table at a time, but if you want to insert multiple rows in a table. In addition to INSERT INTO you will combine it with the select statement.

Let’s see the Syntax for sql insert into select:

INSERT INTO "table 1" ("column1", "column2",....)  
SELECT "column3", "column4",....  
FROM "table2";  

The INSERT INTO statement also contain clauses like SELECT, GROUP BY, HAVING as well as JOIN and ALIAS. So the insert into select statement may be complicated some times.