Consider the below query:
Select
Case when left(‘152rew’, 5) not like ‘%[^A-Za-z]%’
then ‘true’
else ‘false’
end
How ^ this is working in above SQL statement as it is returning false.
Can someone help me with this?
Consider the below query:
Select
Case when left(‘152rew’, 5) not like ‘%[^A-Za-z]%’
then ‘true’
else ‘false’
end
How ^ this is working in above SQL statement as it is returning false.
Can someone help me with this?
In the LIKE syntax used in SQL Server you can indeed use a character class.
For example:
x LIKE '%[A-Z]%'
Which would be true if x contains at least 1 letter.
Btw, this example assumes a case-insensitive collation.
The ^
at the start of the [...]
is used as a negation of that.
F.e.
x LIKE '%[^A-Z]%'
Which would be true if x contains at least one character that is NOT a letter.
So then when negating the negation:
x NOT LIKE '%[^A-Z]%'
It's like looking for x that only contain letters, or is an empty string. In other words: x most NOT contain a character that is NOT a letter.
But something as ‘152rew’ also contains digits, so it's false.
Select Case when left('152rew',5) not like '%[^A-Za-z]%' then 'true' else 'false' end
left('152rew',5)
would be 152re
which doesn't match the regex '%[^A-Za-z]%'
because:
'%[^A-Za-z]%'
would be matched against the words that contain letters only (A-Z) since it has a-z
that would make it case-insensitive so it will accepts all the letters from A to Z i.e capital as well as small.
As it doesn't match '%[^A-Za-z]%'
so true is returned.
SQL Server allows character classes in LIKE
. '%[A-Za-z]%'
means "contains a letter". ^
negates the expression. '%[^A-Za-z]%'
means "contains a non-letter".
Hence your CASE
expression is this in pseudo code:
if '152re' doesn't contain a "non-letter" then 'true' else 'false' end if
Or simpler:
if '152re' contains a "non-letter" then 'false' else 'true' end if
1
, 5
, and 2
are not letters, so the string contains a "non-letter"; the expression returns 'false'.