Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are the following SQL queries not equivalent?

Tags:

sql

postgresql

SELECT c.cname
FROM Customers c
WHERE c.age > ALL (SELECT c2.age
 FROM Customers c2
 WHERE c2.type = 'snowboard'); 

SELECT c.cname
FROM Customers c
WHERE c.age > (SELECT MAX(c2.age)
 FROM Customers c2
 WHERE c2.type = 'snowboard')

They look the same to me because MAX(c2.age) is greater or equal than all the values in the column ages and if c.age is greater than MAX(c2.age) then it's greater than all the values.

like image 905
daniel Avatar asked Feb 14 '17 22:02

daniel


People also ask

What is not equal to in SQL query?

The SQL Not Equal comparison operator (!=) is used to compare two expressions. For example, 15 != 17 comparison operation uses SQL Not Equal operator (!=) between two expressions 15 and 17.

How do you write equivalent in SQL query?

In SQL, you can use the >= operator to test for an expression greater than or equal to. Let's use the same customers table as the previous example.

How do you write not equal to in SQL Server?

!= (Not Equal To) (Transact-SQL) - SQL Server | Microsoft Docs.

Is <> the same as != In SQL?

Here is the answer – Technically there is no difference between != and <>. Both of them work the same way and there is absolutely no difference in terms of performance or result.


1 Answers

If there are no matches for snowboard, then the first returns all rows and the second returns none.

The logic for the first follows the colloquial definition of "all". If there are no matches, then any value is greater than the (non-existent) value from the subquery. Note: this is even true of NULL (at least in SQL Server).

The second query returns NULL when there are no matches. Basically, comparisons to NULL never return true -- well, there are a few exceptions.

Hint for the future: if two queries look like they are the same, but don't return the same values, then one of two things is usually the culprit:

  • NULL values is involved
  • One of the tables is empty
like image 154
Gordon Linoff Avatar answered Sep 28 '22 05:09

Gordon Linoff