Sql INSERT

Sql INSERT
Nikhil
Published on 2021-08-14 15:12:53

Section 26.1: INSERT data from another table using SELECT

INSERT INTO Customers (FName, LName, PhoneNumber)

SELECT FName, LName, PhoneNumber FROM Employees

This example will insert all Employees into the Customer's table. Since the two tables have different fields and you don't want to move all the fields over, you need to set which fields to insert into and which fields to select. The correlating field names don't need to be called the same thing, but then need to be the same data type. This example is assuming that the Id field has an Identity Specification set and will auto-increment.

If you have two tables that have exactly the same field names and just want to move all the records over you can

use:

INSERT INTO Table1
SELECT * FROM Table2
Section 26.2: Insert New Row
INSERT INTO Customers
VALUES ('Zack', 'Smith', '[email protected]', '7049989942', 'EMAIL');

This statement will insert a new row into the Customers table. Note that a value was not specified for the Id column, as it will be added automatically. However, all other column values must be specified.

Insert Only Specified Columns

INSERT INTO Customers (FName, LName, Email, PreferredContact)
VALUES ('Zack', 'Smith', '[email protected]', 'EMAIL');

This statement will insert a new row into the Customers table. Data will only be inserted into the columns specified - note that no value was provided for the PhoneNumber column. Note, however, that all columns marked as not null must be included.

Insert multiple rows at once

Multiple rows can be inserted with a single insert command:

INSERT INTO tbl_name (field1, field2, field3)
VALUES (1,2,3), (4,5,6), (7,8,9);

For inserting large quantities of data (bulk insert) at the same time, DBMS-specific features and recommendations exist.

ATutorialHub Related Guide

Comments (8)

Leave a Comment

Your email address will not be published. Required fields are marked*

User Comments

html tutorial comments

panduranga gupta

2021-07-05 07:03:13

good website for learning and help me a lot

html tutorial comments

raju

2021-09-25 14:58:47

The awsome website i am looking like for a long time, good work atutorialhub team keep doing

html tutorial comments

Shivani

2021-09-01 15:03:56

Learning a lot from the courses present on atutorialhub. The courses are very well explained. Great experience

html tutorial comments

Harshitha

2021-09-10 15:05:45

It is very helpful to students and easy to learn the concepts

html tutorial comments

Sowmya

2021-09-14 15:06:41

Great job Tutorials are easy to understand Please make use of it

html tutorial comments

Zain Khan

2021-09-18 15:07:23

Great content and customized courses.

html tutorial comments

Rudrakshi Bhatt

2021-09-09 15:08:10

Well structured coursed and explained really well!

html tutorial comments

Pavana Somashekar

2021-09-11 15:09:08

Good platform for beginners and learn a lot on this website