Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape underscore in the string query in hibernate and SQL?

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.

like image 281
user2323036 Avatar asked Jun 14 '13 06:06

user2323036


People also ask

How do I escape a special character in a string in SQL?

Use braces to escape a string of characters or symbols. Everything within a set of braces in considered part of the escape sequence. When you use braces to escape a single character, the escaped character becomes a separate token in the query. Use the backslash character to escape a single character or symbol.

What does _ represent in SQL?

The underscore character ( _ ) represents a single character to match a pattern from a word or string. More than one ( _ ) underscore characters can be used to match a pattern of multiple characters.

How do I match an underscore in SQL?

If you are searching for an underscore then escape it with a '\' so you would search for' \_'. When matching SQL patterns, you can use these symbols as placeholders: % (percent) to substitute for zero or more characters, or _ (underscore) to substitute for one single character.

Why is underscore _ used to query the database?

The underscore allows for the substitution of a single character in an expression.


1 Answers

Have you tried escaping it:

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

\_ instead of just _.

like image 114
Michał Powaga Avatar answered Sep 21 '22 05:09

Michał Powaga