sqloracle-databaseoracle-sqldeveloperregexp-like

Oracle SQL REGEXP for finding a value between columns, irrespective of their position


I have following set of data in two different columns in a table. I need to check if the BB% value is matching between both the columns or not.

Column A Column B
BB12,AA13,CC24 AA13,BB12,CC24
BB99,AA34,CC78 AA34,CC78,BB77
AA22,BB33,CC77 AA22,BB33,BB44,CC77

I initially tried using below REGEXP. But this will only work if the BB value in column A is always in position 1 and in Column B with position 2. But I need a REGEXP to check something for row 2 and row 3 scenarios.

REGEXP_SUBSTR(ColumnA, '\w+', 1, 1) <> REGEXP_SUBSTR(ColumnB, '\w+', 1, 2)

Solution

  • You can try this. But, it does not take account the case there are more than one occurrence of BBXXX in the columnA. In such a case, the comparison will only be based on the first occurence of BBXXX in the columnA.

    with your_table (ColumnA, ColumnB) as (
    select 'BB12,AA13,CC24',    'AA13,BB12,CC24' from dual union all
    select 'BB99,AA34,CC78',    'AA34,CC78,BB77' from dual union all
    select 'AA22,BB33,CC77',    'AA22,BB33,BB44,CC77' from dual union all
    select 'AA22,BB33,CC77',    'AA22,BB44,BB33,CC77' from dual union all
    select 'AA22,BB33,CC77',    'BB33,AA22,BB44,CC77' from dual
    )
    select COLUMNA, COLUMNB
    from your_table t
    where ','||COLUMNB||',' NOT like '%,'||regexp_substr(COLUMNA, 'BB[^,]*', 1, 1)||',%'
    ;