5

I am trying to select from a table with the following structure :

MATERIALS 
id
shortname 
longname

all the lines where the long name is like the short name.

I've tried the solution presented here : Dynamic Like Statement in SQL , but it doesn't work for me.

SELECT * from MATERIALS where longname like (shortname + '%');

doesn't work in Oracle.

1
  • 2
    I found the answer in the meantime : select * from materials where longname like CONCAT(upper(shortname), '%'); Commented Nov 30, 2011 at 14:42

3 Answers 3

13

You can use the CONCAT() function:

SELECT * 
FROM MATERIALS 
WHERE longname LIKE CONCAT(shortname, '%')

or even better, the standard || (double pipe) operator:

SELECT * 
FROM MATERIALS 
WHERE longname LIKE (shortname || '%')

Oracle's CONCAT() function does not take more than 2 arguments so one would use the cumbersome CONCAT(CONCAT(a, b), c) while with the operator it's the simple: a || b || c

Sign up to request clarification or add additional context in comments.

Comments

2

CONCAT() is probably the most technically correct.

For convenience, however, ORACLE does have an equivalent operator to +...

SELECT * 
FROM MATERIALS 
WHERE longname LIKE (shortname || '%')

1 Comment

If I am not wrong || is the technically correct and + is non-standard.
0

It may be worth mentioning that neither of the above worked for me in an Oracle 19c database today.

SITUATION
I had created a function that I could query like a table. (A PIPELINED function returning a custom data type). In the loop to return a (modified) row of data, I wanted to take a parameter from the function call and use a LIKE to identify the right data.

I started with hard coded values, and everything worked fine. When I moved to dynamically assigning the value for the like, in the ways mentioned in the answer by @MatBailie and @ypercube™. Neither worked.

FIX
What DID work, however was to do the following:

  1. Create a local variable to set the value from the parameter and concatenate in '%' (so the final value was the string passed as well as % @ the end of that string). That code was localVariable := parameterPassedToFunction||'%';
  2. In the query where the LIKE was required I used the following: LIKE''||localVariable

Hope that helps someone in the future.

1 Comment

Chat GPT may benefit... as apparently the company behind the Stack Exchange network has signed an agreement to allow OpenAI access to all of our answers & questions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.