Eric F
Eric F

Reputation: 948

How to insert records using a SELECT statement?

Background

I currently have a table named Parts_list that is structured as shown below:

enter image description here

_id is autoincrementing so I always provide NULL which works fine.

I would like to use a SELECT statement to populate this table but have difficulties how to write the INSERT SELECT statement.

What I have tried

For testing I have tried this SQL statement:

INSERT INTO Parts_list VALUES 
   (null, 'My Name',CURRENT_TIMESTAMP, null, null, null, null, 
    null, null, null, null, null, null, null, null, 
    null, null, null, null, null, null, null, null, 
    null, null, null,null, null, null)

and it inserts a new line without any problem.

Problem

However when I try something like this:

INSERT INTO Parts_list VALUES 
(null, 'My Name',CURRENT_TIMESTAMP, Part_ID, null, null, null, 
 null, null, null,null, null, null, null, null, null, null, 
 null, null, null, null, null, null, null, null, null, null, 
 null, null) 
SELECT Part_ID FROM tracking_vehicles

where I am selecting one column and trying to insert this column, nothing happens. Do I have something wrong with my syntax? In my example "Part_ID" is VARCHAR, which matches the data type that it is being inserted to. Any help or guidance is appreciated.

PS I also tried this:

INSERT INTO Parts_list 
(null, 'My Name',CURRENT_TIMESTAMP, Part_ID, null, 
 null, null, null, null, null,null, null, null, null, 
 null, null, null, null, null, null, null, null, null, 
 null, null, null,null, null, null) 
 SELECT Part_ID FROM tracking_vehicles

without the word "VALUES" as I saw many examples not use that, but it doesn't work. Even when I try my first example without "VALUES" it doesn't work either so I am guessing that I need that.

Upvotes: 0

Views: 581

Answers (1)

Bugs
Bugs

Reputation: 4489

Using the example provided here I suggest you use the following syntax:

INSERT INTO Parts_list (_id, table_owner, etc) 
SELECT null, 'My Name', etc 
FROM tracking_vehicles

List out all your columns as I've started to and then pass through all the values in the SELECT.

Upvotes: 1

Related Questions