48

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.

2

2 Answers 2

93

Have you tried escaping it:

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

\_ instead of just _.

3
  • 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.
    – Pysis
    Commented Apr 12, 2018 at 20:51
  • is there an inbuilt function? Commented Jan 21, 2019 at 7:48
  • @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%. Commented Dec 2, 2019 at 4:43
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
  • Welcome to SO, we appreciate your input! Please edit your question and add a short explanation of your code.
    – B--rian
    Commented Aug 20, 2019 at 7:06
  • This does not work in MySQL, at least in version 5.5.30.
    – ssurba
    Commented Sep 5, 2022 at 5:59

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.