Search code examples
sqloracle-databasenested-table

select one row from nested table type


my question is there away to select only one record from that column type as default value.

enter image description here

create type t_tel as table of number;

create table users_tel(
user_id number,
user_name varchar2(100),
tel t_tel
) nested table tel store as tel_table;

insert into users_tel(user_id, user_name, tel) values (1, 'Amir', t_tel(987,654,321));

select * from users_tel;

Solution

  • Use a table collection expression to treat the collection in the nested table as if it was a table and join on that. Then you can filter to get one row per user_id:

    SQL Fiddle

    Oracle 11g R2 Schema Setup:

    create type t_tel as table of number;
    
    create table users_tel(
      user_id number,
      user_name varchar2(100),
      tel t_tel
    ) nested table tel store as tel_table;
    
    insert into users_tel(user_id, user_name, tel)
      SELECT 1, 'Amir',  t_tel(987,654,321) FROM DUAL UNION ALL
      SELECT 2, 'Dave',  t_tel(123,456)     FROM DUAL UNION ALL
      SELECT 3, 'Kevin', t_tel()            FROM DUAL;
    

    Query 1:

    SELECT user_id,
           user_name,
           tel_no
    FROM   (
      SELECT u.*,
             t.column_value AS tel_no,
             ROW_NUMBER() OVER ( PARTITION BY u.user_id ORDER BY ROWNUM ) AS rn
      FROM   users_tel u
             LEFT OUTER JOIN
             TABLE( u.tel ) t
             ON ( 1 = 1 )
    )
    WHERE  rn = 1
    

    Results:

    | USER_ID | USER_NAME | TEL_NO |
    |---------|-----------|--------|
    |       1 |      Amir |    987 |
    |       2 |      Dave |    123 |
    |       3 |     Kevin | (null) |