Popplar
Popplar

Reputation: 279

Massive insertion using value from another table?

is there a simple way to make insert to a table using values from another table? Lets say I have to fetch the NAME value from T1 and I want to make a hardcoded insertion to another table using that value. The insertion values should be something like INSERT INTO T2 (NAME, AGE, GENDER) VALUES (NAME, 22, 'M') Name is fetched from T1, 22 and 'M' are hardcoded in the insert query.

Upvotes: 1

Views: 72

Answers (3)

JCMC
JCMC

Reputation: 46

You can do a select in an insert:

INSERT INTO T2 (NAME, AGE, GENDER) 
SELECT NAME, 22, 'M' FROM T1

Also handy because you can ditch the insert and just run the select to test what you are importing before you do it, and easy to add a WHERE NOT EXISTS to make it idempotent.

Upvotes: 3

Mureinik
Mureinik

Reputation: 312259

You can use an insert-select statement, where you select literals for the values you want:

INSERT INTO t2
SELECT name, 22, 'M'
FROM   t1

Upvotes: 2

Gordon Linoff
Gordon Linoff

Reputation: 1271151

Yes . . . insert . . . select:

insert into t2 (name, age, gender)
   select name, 22, 'M'
   from t1;

Upvotes: 3

Related Questions