I am learning SQL(without concrete implementation).
I need to validate that some value contains only characters using LIKE or NOT LIKE
1.Incorrect example is:
SELECT * FROM table WHERE name LIKE '%[a-zA-Z]'
because '123A123' would be true
2. I read up that It would work
SELECT * FROM table WHERE name NOT LIKE '%[^a-zA-Z]%'
These queries look equal to me(It's like to compare 5 and --5)
Could you explain please what is the difference between?
3条答案
按热度按时间fhg3lkii1#
Ok, let's dissect this:
The regexp here is "does not contain any letters". If we negate using
NOT LIKE
, it'll mean "contains only letters".Now:
Regexp here means "contains at least one letter". So
LIKE
on that will mean the same thing.So:
This will return both
A123
(there's an A) andAAA
, but neither123
(only digits) nor,
(still not a letter) will get returned.This one will only return
AAA
because it's the only one containing letters only.AAA
is the only record that regexp will not match, and since we're negating withNOT LIKE
, it means only this one meets theWHERE
condition.wqlqzqxt2#
This expression:
matches all names that have a character that is not a letter, such as
.
or;
or whatever.This expression:
matches all names that contain at least one letter.
So,
'ABC.DEF'
will match both patterns -- it matches the first because it has.
and the second because it has a letter.However,
'ABC'
does not match the first pattern because it only consists of letters. It does match the second one.qqrboqgw3#
Following condition will check whether your column value has any string character from a-z or A-Z in it.