3

I have this behavior in PostgreSQL 9.3:

-- (1) this "doesn't" work
select 't\om' like '%t\om%'
-- result = false

-- (2) this works
select 't/om' like '%t/om%'
-- result = true

Why is the (1) query result false? What is the best way to get true in (1) query?

Aldwoni
  • 1,168
  • 10
  • 24
sunrelax
  • 65
  • 9

2 Answers2

5

The \ has no special meaning in SQL except inside the condition for the LIKE operator where it can be used to escape the wildcard characters.

But you can define a different escape character for LIKE which then makes the \ a "normal" character:

select 't\om' like '%t\om%' escape '#';

edit

As Sunrelax has commented, you can also use an empty string as the "escape" sequence:

select 't\om' like '%t\om%' escape '';
  • 1
    If you want to compare only the two strings with no escape value: select 't\om' like '%t\om%' escape ''; – sunrelax May 02 '17 at 07:28
1

\ is an escape sequence, so you need to escape it, too:

select 't\om' like '%t\\om%';

There is also a configuration option you can set. See Escaping backslash in Postgresql

Community
  • 1
  • 1
msanford
  • 11,803
  • 11
  • 66
  • 93