The LIKE operator selects
observations by comparing the values of a character variable to a
specified pattern, which is referred to as pattern matching. The LIKE
operator is case sensitive. There are two special characters available
for specifying a pattern:
specifies that any
number of characters can occupy that position. The following WHERE
expression selects all employees with a name that starts with the
letter
N
. The names can be of any length.
where lastname like 'N%';
matches just one character
in the value for each underscore character. You can specify more than
one consecutive underscore character in a pattern, and you can specify
a percent sign and an underscore in the same pattern. For example,
you can use different forms of the LIKE operator to select character
values from this list of first names:
The following table
shows which of these names is selected by using various forms of the
LIKE operator:
You can use a SAS character
expression to specify a pattern, but you cannot use a SAS character
expression that uses a SAS function.
You can combine the
NOT logical operator with LIKE to select values that do not have the
specified pattern, such as the following:
where frstname not like 'D_an%';
Because the % and _
characters have special meaning for the LIKE operator, you must use
an escape character when searching for the % and _ characters in values.
An escape character is a single character that, in a sequence of characters,
signifies that what follows takes an alternative meaning. For the
LIKE operator, an escape character signifies to search for literal
instances of the % and _ characters in the variable's values instead
of performing the special-character function.
For example, if the
variable X contains the values
abc
,
a_b
, and
axb
, the
following LIKE operator with an escape character selects only the
value
a_b
. The escape character (/)
specifies that the pattern searches for a literal ' _' that is surrounded
by the characters
a
and
b
. The escape character (/) is not part of the search.
where x like 'a/_b' escape '/';
Without an escape character,
the following LIKE operator would select the values
a_b
and
axb
. The special character underscore
in the search pattern matches any single
b
character, including the value with the underscore:
where x like 'a_b';
To specify an escape
character, include the character in the pattern-matching expression,
and then the keyword ESCAPE followed by the escape-character expression.
When you include an escape character, the pattern-matching expression
must be enclosed in quotation marks, and it cannot contain a column
name. The escape-character expression evaluates to a single character.
The operands must be character or string literals. If it is a single
character, enclose it in quotation marks.
LIKE 'pattern-matching-expression' ESCAPE 'escape-character-expression'