Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my query with LIKE '%\_' return all rows and not just those ending in an underscore?

Tags:

sql

postgresql

I currently have the query running on Postgres:

SELECT * FROM addenda.users WHERE users.username LIKE '%\_' 

But rather then returning just entries ending in an underscore, I get all results back, regardless of whether it contains an underscore or not.

Running the query below returns a username which is just an underscore, so the escaping does work:

SELECT * FROM addenda.users WHERE users.username LIKE '\_' 

And running the query below returns a username which ends with a specific letter (s):

SELECT * FROM addenda.users WHERE users.username LIKE '%s' 

What am I doing wrong?

like image 332
Hates_ Avatar asked Jan 27 '09 11:01

Hates_


People also ask

How do you underscore in like Operator?

The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards often used in conjunction with the LIKE operator: The percent sign (%) represents zero, one, or multiple characters. The underscore sign (_) represents one, single character.

Can you use _ in SQL?

To broaden the selections of a structured query language (SQL-SELECT) statement, two wildcard characters, the percent sign (%) and the underscore (_), can be used.

How do I query 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.

Is underscore a special character in SQL?

SQL Server T-SQL Wildcard Characters Unlike literal characters, wildcard characters have specific meaning for the LIKE operator. Hence, underscore ('_') in LIKE does not mean a specific regular character, but any single character.


1 Answers

Is your backslash not getting through to PostgreSQL? If you're passing the string through another layer that treats the backslash as an escape character (e.g. a Java String), then that layer may be removing the backslash, and you might need to escape your backslash for that layer.

Do you have any more single character usernames? If the backslash wasn't getting through to PostgreSQL then they would also match '_'

You might be able to try the ESCAPE clause: username LIKE '%!_' ESCAPE '!'

like image 107
Stephen Denne Avatar answered Sep 24 '22 21:09

Stephen Denne