codi05ro
codi05ro

Reputation: 149

Alternative to REGEXP_LIKE in oracle

Can you please tell me if there is any alternative function which I can use for REGEXP_LIKE ?

I have the following situation:

Names:
ID NAME
1  Alex
2  Jim
3  Tom

Invoices:
ID Amount Name_IDs
1  100    1;2;
2  200    2;3;

Wanted output:
Invoice_ID Names     Amount:
1          Alex;Jim; 100
2          Jim;Tom;  200

I know that the database model is not quite technically right, but now I'm using a query for this with REGEXP_LIKE to add in a listagg() the names, but the performance is very very slow.

SELECT inv.id as invoice_id, 
       SELECT listagg(n.name,';') WITHIN GROUP (ORDER BY NULL) from names where REGEXP_LIKE(inv.names, '(^|\W)' || n.name || '(\W|$) 'as names
       inv.amount as amount
from invoices inv;

Can you please give me any idea how to improve this query ?

Thank you!

Upvotes: 0

Views: 2345

Answers (2)

I suggest that you change your data model to something like the following:

NAMES:
ID_NAMES NAME
10       Alex
20       Jim
30       Tom

INVOICES:
ID_INVOICE Amount
1          100
2          200

INVOICE_NAMES:
ID_INVOICE  ID_NAME
1           10
1           20
2           20
2           30

Best of luck.

Upvotes: 1

Frank Ockenfuss
Frank Ockenfuss

Reputation: 2043

If you have an index on your names table then this should be faster:

select i.id,
       i.amount,
       (select listagg(n.name, ';') within group(order by null)
          from (select trim(regexp_substr(str, '[^;]+', 1, level)) ASPLIT
                  from (select i.name_ids as str from dual)
                connect by regexp_substr(str, '[^;]+', 1, level) is not null) t
          join names n
            on n.id = t.asplit)
  from invoices i;

i.e. first split by Name_IDs and join with the names table.

Upvotes: 1

Related Questions