SQL Server question on LIKE vs =

Eric Presser 0 Reputation points
2023-05-23T16:06:12.15+00:00

Why does the 1st query below return no data on SQL Server but the 2nd query below does ? Is this intended to work this way ?

1st query:

select 1

WHERE ('[' LIKE '[');

2nd query:

select 1

WHERE ('[' = '[');

SQL Server Other
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Alberto Morillo 34,671 Reputation points MVP Volunteer Moderator
    2023-05-23T16:11:46.51+00:00

    The character [ and character ] are used to specify a range of values.

    SELECT * FROM Person.EmailAddress WHERE EmailAddress LIKE 'ken[0-9]%'
    
    
    
    

    If you use a query like below it will fail to return data:

    SELECT * FROM Person.EmailAddress WHERE EmailAddress LIKE 'ken[%';
    

    If you enclose the character [ between [ ] it should work you can also use ESCAPE as explained on the article.

    SELECT * FROM Person.EmailAddress WHERE EmailAddress LIKE 'ken[[]%';
    

    The behavior is explained the article here.


  2. Eric Presser 0 Reputation points
    2023-05-23T17:05:18.7566667+00:00

    The actual answer should not include %, so the answer is with the ESCAPE. This will work:

    select 1

    WHERE ('[' LIKE '\[' ESCAPE '[');


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.