Search code examples
sqlsql-like

Are these two SQL Statements equivalent? One works the other doesn't


I'm learning SQL at w3schools. I was studying this chapter: https://www.w3schools.com/sql/sql_having.asp

I decided to use wildcards just to make it interesting. The first SQL statement seems to work when I try it online but not the second. That's why I would like to know if both SQL statements are equivalent or not.

1)

SELECT COUNT(CustomerID) AS Total, Country
FROM Customers
WHERE Country LIKE 'u%' OR Country LIKE 'g%' OR Country LIKE 'f%'
GROUP BY Country
HAVING Total > 5
ORDER BY Total DESC;

2)

SELECT COUNT(CustomerID) AS Total, Country
FROM Customers
WHERE Country LIKE '[ugf]%' 
GROUP BY Country
HAVING Total > 5
ORDER BY Total DESC;

It doesn't show error messsage it only shows "No result." when I try the second SQL statement here: https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_having

The first SQL statement does work.


Solution

  • The two are equivalent only in SQL Server (and Sybase). These extend the LIKE pattern to include character classes (the letters inside the square braces).

    In other databases, LIKE patterns have only two wildcards % and _. The square braces are just that, square braces. It is unlikely that a country name would match them.