Search code examples
oracle-databaseselectrepeatrownum

How can I return multiple identical rows based on a quantity field in the row itself?


I'm using oracle to output line items in from a shopping app. Each item has a quantity field that may be greater than 1 and if it is, I'd like to return that row N times.

Here's what I'm talking about for a table

product_id, quanity
1, 3,
2, 5

And I'm looking a query that would return

1,3
1,3
1,3
2,5
2,5
2,5
2,5
2,5

Is this possible? I saw this answer for SQL Server 2005 and I'm looking for almost the exact thing in oracle. Building a dedicated numbers table is unfortunately not an option.


Solution

  • I've used 15 as a maximum for the example, but you should set it to 9999 or whatever the maximum quantity you will support.

    create table t (product_id number, quantity number);
    insert into t values (1,3);
    insert into t values (2,5);
    
    select t.* 
      from t 
        join (select rownum rn from dual connect by level < 15) a 
                                     on a.rn <= t.quantity
    order by 1;