Search code examples
sqloracle-databasesql-like

How to use reverse like in oracle?


Assume that these are records in a table:

id       code
--------------
1         75
2         90
3         901
4         9014
5         90145
6         80

What is the best query to get below result with 90145 value in where clause:

id       code
--------------
2         90
3         901
4         9014
5         90145

Solution

  • From your description it sounds like you want

    where '90145' like code ||'%';
    

    Quick demo with your values an a slightly similar extra value that is excluded:

    with t (id, code) as (
      select 1, '75' from dual
      union all select 2, '90' from dual
      union all select 3, '901' from dual
      union all select 4, '9014' from dual
      union all select 5, '90145' from dual
      union all select 6, '80' from dual
      union all select 7, '902' from dual
    )
    select * from t
    where '90145' like code ||'%';
    
            ID CODE
    ---------- -----
             2 90   
             3 901  
             4 9014 
             5 90145