Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are these two SQL Server queries the same?

Tags:

sql

sql-server

I have written two queries for fetching column values that either do not start with vowels or do not end with vowels.

Query 1:

SELECT DISTINCT CITY
FROM STATION
WHERE city NOT LIKE '[aeiou]%'
   OR city NOT LIKE '%[aeiou]'

Query 2:

SELECT DISTINCT CITY
FROM STATION
WHERE city NOT LIKE '[aeiou]%[aeiou]'

According to me, they should be same query as they pass test cases easily and filter same result. Are these two different queries in any scenario?

like image 737
Kajal_T Avatar asked Aug 18 '26 05:08

Kajal_T


1 Answers

No, they behave differently. I expected some differences with cities like "a", because a string with length 1 will not match pattern [aeiou]%[aeiou], but may match both [aeiou]% and %[aeiou]. Just tried it out, and actually there are differences then. One can still discuss which of both queries interpret 'a' correctly, but at least both queries behave differently:

SELECT *
  FROM (VALUES ('aasfa')
             , ('basda')
             , ('asdfb')
             , ('a')
       ) t1 (c)
       where c  not like '[aeiou]%[aeiou]';

Result:

c
-----
basda
asdfb
a

Query:

SELECT *
  FROM (VALUES ('aasfa')
             , ('basda')
             , ('asdfb')
             , ('a')
       ) t1 (c)
       where c    not  like '[aeiou]%'
or c not  like '%[aeiou]'

Result:

c
-----
basda
asdfb
like image 71
Stephan Lechner Avatar answered Aug 21 '26 02:08

Stephan Lechner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!