1

Table 1:

id    name    desc
------------------
1     a       abc
2     b       def
3     c       adf


Table 2:
name    desc
------------
x       123
y       345

How do I run an sql update query that can update Table 1 with Table 2's name and desc using the id of table 1 and rownum in table2? It's okay to assume that rownum in table2 is the same as id of table 1. So the end result I would get is

Table 1:

id    name    desc
------------------
1     x       123
2     y       345
3     c       adf

Below are scripts for table creation and record insertion

create table table1 (
  id number,
  name varchar2(10),
 desc_ varchar2(10)
);

create table table2 (
  name varchar2(10),
  desc_ varchar2(10)
);

insert into table1 values(1, 'a', 'abc');
insert into table1 values(2, 'b', 'def');
insert into table1 values(3, 'c', 'ghi');

insert into table2 values( 'x', '123');
insert into table2 values( 'y', '456');

Credits to "update one table with data from another"

user2008558
  • 341
  • 5
  • 16

1 Answers1

0

There is no such thing as "rownum" in a table. SQL tables represent unordered sets, so there is no ordering without an ordering column.

Oracle does provide rowid as a built-in column identifier. This is not the same as rownum and is not guaranteed to be in order.

You can use rownum, but the value is not guarantee to have any particular meaning and might change between runs:

update table1
    set (name, desc) = (select name, desc
                        from (select t2.*, rownum as seqnum
                              from table2 
                             ) t2
                        where seqnum = table1.id
                       )
    where id <= (select count(*) from table2);
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • Can you explain why you have the where clause `"where id <= (select count(*) from table2)"` Thanks – user2008558 Jul 22 '18 at 13:23
  • @user2008558 . . . The tables have different numbers of rows. You only want to update the "first" rows where is the number of rows in `table2`. – Gordon Linoff Jul 22 '18 at 13:24