Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

SQL help needed to generate the permutations

RanagalMay 31 2018 — edited Jun 4 2018

Hi Experts,

I have the below scenario:

drop table table_x;

/

create table table_x(col1)

as

select 'A' from dual

union all

select 'B' from dual

union all

select 'C' from dual

union all

select 'D' from dual;

/

Input: A number say 1,2,3...n where n is no of elements in the table_x and can reach up to count(table_x.col1)

Output:

Case 1:

                Input: 1

                Output:                    A

                                                B

                                                C

                                                D

Case 2:

                Input: 2

                Output:                    AB

                                                AC

                                                AD

                                                BA

                                                BC

                                                BD

                                                CA

                                                CB

                                                CD

                                                DA

                                                DB

                                                DC

Logic:

The query should be able to produce the permutations whenever the user provides the number like above.

My attempt:

SELECT val

FROM   (SELECT Ltrim(Sys_connect_by_path(col1, ' '), ' ') AS VAL, LEVEL LV

             FROM   (SELECT col1,ROWID RD FROM table_x)

             CONNECT BY LEVEL <= (SELECT Count(1) FROM table_x)

             AND PRIOR rd <> rd

             AND PRIOR Sys_guid() IS NOT NULL)

WHERE  lv = :user_provided_number;

Question:

  1. Is this the right way to solve this problem ? If not, then what is ? And how ?
  2. Since the query takes a considerable amount of time to produce the results, is there any better method to achieve it ?

Note:

  1. Oracle Database 11g Enterprise Edition Release 11.2.0.4.0 - 64bit Production

Appreciate the help. Thanks in advance.

This post has been answered by mathguy on May 31 2018
Jump to Answer
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jul 2 2018
Added on May 31 2018
26 comments
2,816 views