SQL insert query

I am struggling with this piece of SQL, and I was wondering if anyone could help me.

INSERT INTO table_1(
rec_1, 
rec_2, 
rec_3
) 
VALUES (
val_1, 
val_2, 
val_3
) 

Now rec_2 and rec_3 are clear and have absolute values. Rec_1 is populated with values ​​from another table. Now I want to insert values ​​from another table that do not yet exist in this table. I assumed that I should use WHERE NOT IN?

So, it will be something like this:

INSERT INTO table_1(
rec_1, 
rec_2, 
rec_3
) 
VALUES (
val_1,
val_2, 
val_3
) 
WHERE NOT IN (
SELECT rec FROM table_2
)

But .. How can I insert these values ​​in rec_1 in my query?

+3
source share
4 answers

How about simple INSERT/SELECT, if rec_2they rec_3are absolute values:

INSERT INTO table_1 (rec_1, rec_2, rec_3)
SELECT val_1, 'val_2', 'val_3'
FROM other_table
WHERE val_1 NOT IN (SELECT rec_1 FROM table_1)
+5
source
INSERT INTO table_1(rec_1, rec_2, rec_3) 
SELECT val_1, val_2, val_3 FROM dual WHERE NOT EXISTS (SELECT rec FROM table_2)

You can check this answer for future reference.

More here

+4

INSERT INTO table_1(rec_1, rec_2, rec_3) 
SELECT  val_1, val_2, val_3 FROM tablename 
WHERE NOT EXISTS (SELECT rec FROM table_2)
+2
     4 ways to insert record
 1--> {Simple Insertion when table column sequence is known}
        Insert into Table1
        values(1,2,...)

    2--> {Simple insertion mention column}  
        Insert into Table1(col2,col4)
        values(1,2)

    3--> {bulk insertion when num of selected collumns of a table(#table2) are equal to Insertion table(Table1) }   
        Insert into Table1 {Column sequence}
        Select * -- column sequence should be same.
           from #table2

    4--> {bulk insertion when you want to insert only into desired column of a table(table1)}
        Insert into Table1 (Column1,Column2 ....Desired Column from Table1)  
        Select Column1,Column2..desired column from #table2
           from #table2
0

All Articles