Link to home
Start Free TrialLog in
Avatar of SuperLight
SuperLight

asked on

Oracle SQL Insert Script to copy data between tables

Hi All,

I have created a simple insert query to move the contents of table A into table B (there is some additions made in this process).

INSERT INTO TABLE B (Col A, Col B, Col C, Col D)
SELECT Col A, Col B, Col C,'Fixed' FROM TABLE A

Open in new window


However, this scrambles the order of the rows.  The order is important because it represents a parent-child relationship.  What do I need to change to maintain the row order?

Thanks,
Mark
Avatar of slightwv (䄆 Netminder)
slightwv (䄆 Netminder)

>>What do I need to change to maintain the row order?

Add an order by in the select?
ASKER CERTIFIED SOLUTION
Avatar of johnsone
johnsone
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
What johnsone said but I was creating a test case to show it.

Can you explain why you think insert order matters?  Are you getting some constraint error?

Here is a simple test showing the order doesn't matter:
drop table tab1 purge;
create table tab1
  (
     id      number primary key,
     child number references tab1(id)
  );

insert into tab1 values(1,1);
insert into tab1 values(2,1);
insert into tab1 values(3,2);
commit;



drop table tab2 purge;
create table tab2
  (
     id      number primary key,
     child number references tab2(id)
  );

insert into tab2 select * from tab1 order by child desc;
commit;

Open in new window

Avatar of SuperLight

ASKER

Thanks for the clarification!  Easy points ;o)
For information, the table contains metadata that is used to build a hierarchy (Parent-Child format) therefore the order must be maintained otherwise the child will appear before the parent.

Thanks,
Mark
>> therefore the order must be maintained otherwise the child will appear before the parent.

Insert order shouldn't matter with an insert as select.  Look at the example I posted.

Now, if you were doing individual inserts then yes, you need to make sure the parent exists before the child.

If you still believe order is important, then why did you select the post that said it didn't matter?
Try changing line 22 to

insert into tab2 select * from tab1 order by I'd, child; commit;
Ghunaima,

First:  This question is closed.
Second:  You commented on a test case showing that in this case, insert order doesn't matter.  The order by in the test case was as I intended it.