Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating incremental numeric column values during INSERT SELECT statement

I need to copy some data from one table to another in Oracle, while generating incremental values for a numeric column in the new table. This is a once-only exercise with a trivial number of rows (100).

I have an adequate solution to this problem but I'm curious to know if there is a more elegant way.

I'm doing it with a temporary sequence, like so:

CREATE SEQUENCE temp_seq
    START WITH 1;

INSERT INTO new_table (new_col, copied_col1, copied_col2)
    SELECT temp_seq.NEXTVAL, o.*
      FROM (SELECT old_col1, old_col2
              FROM old_table,
          ORDER BY old_col1) o;

DROP SEQUENCE temp_seq;

Is there way to do with without creating the sequence or any other temporary object? Specifically, can this be done with a self-contained INSERT SELECT statement?

Please consider a trigger to be a non-option.

MORE INFO: I would like to control the order that the new rows are inserted, and it won't be the same order they were created in the old table (note I've added the ORDER BY clause above). But I still want my new sequential column to start from 1.

There are similar questions, but I believe the specifics of my question are original to SO.

like image 200
Igby Largeman Avatar asked May 03 '10 19:05

Igby Largeman


1 Answers

You can use ROWNUM. This pseudo-column numbers the rows in your result:

Insert Into new_table (new_col, copied_col1, copied_col2)
    Select Rownum, old_col1, old_col2
    From old_table;

If you want your records to be sorted, you need to use a sub-query:

Insert Into new_table (new_col, copied_col1, copied_col2)
    Select Rownum, old_col1, old_col2
    From (
        Select old_col1, old_col2
        From old_table
        Order By old_col1
    );
like image 87
Peter Lang Avatar answered Oct 19 '22 15:10

Peter Lang