Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for a substring in a string in Oracle without LIKE

Tags:

sql

oracle

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?

like image 640
Richard Knop Avatar asked Oct 15 '09 12:10

Richard Knop


People also ask

How do you check a string contains a substring in Oracle?

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>)

How check substring in PL SQL?

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.

What is substr () Instr () functions?

The substr functions allows you to extract a substring from a string. The instr function returns the location of a substring in a string.


3 Answers

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.

like image 104
wefwfwefwe Avatar answered Oct 20 '22 20:10

wefwfwefwe


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').

like image 28
Dave Costa Avatar answered Oct 20 '22 20:10

Dave Costa


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. :-)

like image 7
darreljnz Avatar answered Oct 20 '22 20:10

darreljnz