Search code examples
sqloracleoracle11g

How can I get the unique characters from a string in Oracle?


How to get the unique characters from a string in Oracle?

Lets say I have a column with data

CCCXXXCCCCCCCCCCCCCCCCXXCCCCCCCCCCCCCCCCCCCCCCC

and I want to return 'CX' as the list of unique characters.

likewise: aaaabbbccccdddaaa ==> abcd , HelloO ==> HeloO

Order is important, I want them to be in the same order as they first appear in the string.

Is there any way to do it without using stored procedure?

Edit: add more examples


Solution

  • SELECT SUBSTR(REGEXP_SUBSTR('CCCCXXXCCCCCCCCCCCCCCCCXXCCCCCCCCCCCCCCCCCCCCCCC', '^(.)\1*.'), -2, 2) RESULT
    FROM DUAL;
    

    It returns CX

    Here is another solution:

    Select Replace (Wm_Concat (C), ',', '')
    From
      (Select Substr ('CCCXCCCXXXCCCCCCCCCCCCCCCCXXCCCCCCCCCCCCCCCC', Rownum, 1) C,
        Min (Rownum) Rn
      From Dual
        Connect By Rownum <= Length ( 'CCCXCCCXXXCCCCCCCCCCCCCCCCXXCCCCCCCCCCCCCCCC')
      Group By Substr ( 'CCCXCCCXXXCCCCCCCCCCCCCCCCXXCCCCCCCCCCCCCCCC', Rownum, 1)
      Order By Rn
      ) X;
    

    It returns all the unique chars in order of their occurence. Btw, yes, it looks horrible