SQL INSERT Statement
Introduction
SQL INSERT statement is used to insert a data into a table.
The two ways to insert a data in a table are:
1. Inserting data with SELECT statement.
INSERT INTO SELECT statement selects data from one table to another table (existing table).
Syntax:
i) To copy all columns from one table to another table.
INSERT INTO table_3
SELECT * FROM table_1;
ii) To copy only few columns into another columns.
SELECT INTO table_3
(column_1, column_2, column_3........)
FROM table_1;
Example : Query to insert a data with SELECT Statement.
Consider the following Table1 and Table2.
Write a query to insert a few columns of table 2 into table 1 such as Last_Name, First_Name and country.
Table 1:
Client_ID | Last_Name | First_Name | Contact | Country |
---|
1 | Patil | Ravi | 600000 | India |
2 | Morya | Surendra | 230000 | India |
3 | Singh | Jaya | 780000 | India |
4 | Pandit | Prajakta | 550000 | India |
Table 2:
Client_ID | Last_Name | First_Name | Contact | Country |
---|
1 | Thomas | Alex | 2400000 | USA |
2 | Cruise | Martin | 5600000 | USA |
INSERT INTO Table1(Last_Name, First_Name, Country)
SELECT Last_Name, First_Name, Country FROM Table2;
The result is shown in the following table.
Client_ID | Last_Name | First_Name | Contact | Country |
---|
1 | Patil | Ravi | 600000 | India |
2 | Morya | Surendra | 230000 | India |
3 | Singh | Jaya | 780000 | India |
4 | Pandit | Prajakta | 550000 | India |
5 | Thomas | Alex | null | USA |
6 | Cruise | Martin | null | USA |
2. Inserting data without SELECT statement.
Syntax:
INSERT INTO Table_name (Column_Name1, Column Name 2)
Values (Value1, Value2);
Example : Inserting data without SELECT Statement.
Consider the following table titled as
'Clients'.
Client_ID | Last_Name | First_Name | Contact | Country |
---|
1 | Thomas | Alex | 2400000 | USA |
2 | Cruise | Martin | 5600000 | USA |
Write a query to insert a data (Values) into columns such as Last_Name, First_Name and country.
INSERT INTO Clients (Last_Name, First_Name, Contact, Country)
Values ('Pandit', 'Prajakta', 2345678, 'India');
The result is shown in the following table.
Client_ID | Last_Name | First_Name | Contact | Country |
---|
1 | Thomas | Alex | 2400000 | USA |
2 | Cruise | Martin | 5600000 | USA |
3 | Pandit | Prajakta | 2345678 | India |