MetaGuru
MetaGuru

Reputation: 43813

Possible to INSERT INTO a table with values from another table?

So say I want to...

insert into tableA, 2 variables from tableB, but only rows that are in tableB that have 1 of the variables equal to a certain thing...

hmm let's see if I can be more specific...

i want to create a new row in tableA with the userid and courseid from tableB for every row of tableB that has a courseid of 11

please advise

Upvotes: 1

Views: 2698

Answers (6)

rakesh
rakesh

Reputation:

insert into tableA(column1,column2,column3) select column1,column2,column3 from table B

Upvotes: 0

vezult
vezult

Reputation: 5243

You may use SELECT INTO if you are creating a new table using existing data:

SELECT <columns here> INTO tableA FROM tableB WHERE <restrictions here>

If you want to insert existing data into an existing table, you must use:

INSERT INTO tableA (<destination columns>) SELECT <source columns> FROM tableB WHERE <restrictions here> 

As described in other answers

Upvotes: 0

OldBuildingAndLoan
OldBuildingAndLoan

Reputation: 3022

You didn't mention which database you're using.

MS Access, for me, has proven to be very buggy when trying to do something like this.

Upvotes: 0

Gregory A Beamer
Gregory A Beamer

Reputation: 17010

INSERT INTO TableA (userid, courseid)

SELECT userid, courseid FROM TableB
WHERE courseid = 11

That should do it for you.

Upvotes: 0

Ian Devlin
Ian Devlin

Reputation: 18870

Well not knowing what columns you have in tableA, I'd say:

insert into tableA
select 
    userid,
    courseid 
from tableB where 
courseid=11

Upvotes: 4

Quassnoi
Quassnoi

Reputation: 425251

INSERT
INTO    tableA (col1, col2)
SELECT  userid, courseid
FROM    tableB
WHERE   courseid = 11

Upvotes: 17

Related Questions