How can I check for a substring in a string in Oracle without using LIKE? Let's say I want to select all users from a table that have the letter "z" in their last name:
SELECT * FROM users WHERE last_name LIKE '%z%';
That would work, but I don't want to use LIKE. Is there some other function I could use?
Check if a text string contains a particular substring at the start of the string. To determine if a particular string is contained at the start of a text variable or text constant, you can use the following syntax with the StartsWith function: StartsWith(<text value>, <text substring>)
The PLSQL INSTR function is used for returning the location of a substring in a string. The PLSQL INSTR function searches a string for a substring specified by the user using characters and returns the position in the string that is the first character of a specified occurrence of the substring.
The substr functions allows you to extract a substring from a string. The instr function returns the location of a substring in a string.
I'm guessing the reason you're asking is performance? There's the instr function. But that's likely to work pretty much the same behind the scenes.
Maybe you could look into full text search.
As last resorts you'd be looking at caching or precomputed columns/an indexed view.
If you were only interested in 'z', you could create a function-based index.
CREATE INDEX users_z_idx ON users (INSTR(last_name,'z'))
Then your query would use WHERE INSTR(last_name,'z') > 0
.
With this approach you would have to create a separate index for each character you might want to search for. I suppose if this is something you do often, it might be worth creating one index for each letter.
Also, keep in mind that if your data has the names capitalized in the standard way (e.g., "Zaxxon"), then both your example and mine would not match names that begin with a Z. You can correct for this by including LOWER in the search expression: INSTR(LOWER(last_name),'z')
.
You can do it this way using INSTR:
SELECT * FROM users WHERE INSTR(LOWER(last_name), 'z') > 0;
INSTR returns zero if the substring is not in the string.
Out of interest, why don't you want to use like?
Edit: I took the liberty of making the search case insensitive so you don't miss Bob Zebidee. :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With