user1620464
user1620464

Reputation: 49

Executing Insert into statement in SQL resulting in nulls for other columns

i am trying to use an insert into a column where the data for other columns already exists, but the data is not populating adjacent to the other columns, instead data is inserted after all the data in the table. For example:

select * from tab1;       
ID NAme Last_name          
1  King                     
2  Queen                   
3  Rook 

select * from tab2;
Id LastName_Name
1  Abc 
2  def
3  xyz

SQL : Insert into tab1 (Last_name)
select tab2.LastName_Name from tab1,tab2, where tab1.Id=tab2.Id

Output:
Id Name Last_Name
1  King   NULL
2  Queen  NULL
3  Rook   NULL
4  NULL   Abc
5  NULL   def
6  NULL   xyz

But I want the data as below:

Id Name Last_Name
1  King   Abc
2  Queen  def
3  Rook   xyz

Any work around for this? thanks in advance :)

Step2:

select * from tab1;

ID Name Id2

1 King NA

2 Queen NA

3 Rook NA

select * from tab2;

ID 

1  

2  

3  

4

5

6

I want the Output data as below:

The ID data in tab2 should populate in tab1 column (ID2) which are matching with TAB1.ID column values as below:

Id Name ID2
1  King   1
2  Queen  2
3  Rook   3

Can you please provide any query for this?

Upvotes: 0

Views: 106

Answers (2)

Chris
Chris

Reputation: 2952

You don't need an INSERT you need an UPDATE statement:

UPDATE tab1 SET tab1.Last_name = tab2.LastName_Name
FROM tab1 INNER JOIN tab2 ON tab1.Id = tab2.Id

Upvotes: 1

AdaTheDev
AdaTheDev

Reputation: 147224

So you are wanting to UPDATE the rows in tab1 with the corresponding last names from tab2?

In which case, use an UPDATE statement instead of an INSERT:

UPDATE tab1
SET tab1.Last_name = tab2.LastName_Name
FROM tab1
    JOIN tab2 ON tab1.Id = tab2.Id

Upvotes: 1

Related Questions