0

I can guesss it may be easy to answer type question but I am facing it first time, so any help will be more appreciated.

My Query:

SELECT remarks FROM enroll WHERE remarks LIKE 'REC_%'

OUTPUT:

remarks
REC_59161
Reclassify Hedge

Expected Output is only REC_59161. Yes _ is used for matching any single character but I am just looking for achieving my expected output.

Kara
  • 6,115
  • 16
  • 50
  • 57
Shushil Bohara
  • 5,556
  • 2
  • 15
  • 32
  • Underscore `_`, is a wildcard. Why don't you want Reclassify Hedge? Wrong case, or no underscore? – jarlh May 26 '17 at 08:33

4 Answers4

3

_ is a wildcard Character. So that you have to escape it using [].

Query

select remarks
from enroll
where remarks like 'REC[_]%';
Ullas
  • 11,450
  • 4
  • 33
  • 50
2

The underscore _ character is actually a special character with the LIKE operator, as are %, [] and ^:

https://learn.microsoft.com/en-us/sql/t-sql/language-elements/like-transact-sql

In that article, you'll see that an underscore _ matches any single character.

Use the ESCAPE keyword to define an escape character to allow you to escape the pattern-matching characters. We can use ! as the escape character, so:

WHERE remarks LIKE 'REC!_%' ESCAPE '!'
Dai
  • 141,631
  • 28
  • 261
  • 374
1

_ is a wildcard character, Try this :

declare @enroll table (remarks varchar(50));
insert into @enroll values ('REC_59161') , ('Reclassify Hedge');
SELECT remarks FROM @enroll WHERE remarks LIKE 'REC[_]%';

Demo

Ilyes
  • 14,640
  • 4
  • 29
  • 55
0

There are two issues:

  1. It seems that the column is case insensitive, see Is the LIKE operator case-sensitive with MS SQL server? for details. That's why Rec in Reclassify Hedge fits REC in the Like
  2. _ (as well as %) is a wild card, you should escape _ in the pattern

Query:

  SELECT remarks 
    FROM enroll 
   WHERE remarks LIKE 'REC*_%' ESCAPE '*' /* SQL 92 standard */

http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt

uses the triadic operator LIKE (or the inverse, NOT LIKE), operating on three character strings and returning a Boolean. LIKE determines whether or not a character string "matches" a given "pattern" (also a character string). The characters '%' (percent) and '_' (underscore) have special meaning when they occur in the pattern. The optional third argument is a character string containing exactly one character, known as the "escape character", for use when a percent or underscore is required in the pattern without its special meaning.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215