49

The _ (underscore) given in the SQL query is not honored.

Example :

SELECT * FROM employee WHERE NAME LIKE '%k_p%';

This matches and brings many rows apart from rows which contain k_p

Could someone please assist on how to achieve this in SQL and also in Hibernate? Thanks.

3

2 Answers 2

96

Have you tried escaping it:

SELECT * FROM employee WHERE NAME LIKE '%k\_p%';

\_ instead of just _.

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

3 Comments

My string had several underscores that I wanted to treat literally, but I also wanted to match % somewhere in there, and didn't want to do lots of escaping. I found I can use RLIKE instead of LIKE and just use the Regex syntax .* instead of %, and input the underscores plainly. I might prefer this in SQL from now on since like JSON, I might prefer Regex as another common tool to use for any situation.
is there an inbuilt function?
@Pysis .* is implicit. You can substitute rlike 'k_p' for like '%k\_p%', and also k_p$ for %k_p, and ^k_p for k_p%.
0

I know it is quite late but can be solution for other programmers. You can try

SELECT * FROM employee WHERE NAME LIKE '%k[_]p%';

2 Comments

Welcome to SO, we appreciate your input! Please edit your question and add a short explanation of your code.
This does not work in MySQL, at least in version 5.5.30.

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.