-2

I only have a month of learning experience on sql server and I was just wondering why the first query before produces the right results (i.e. join two table and only select rows from left table that does NOT have a matching row), whereas the second query returns an empty query.

First

select R.Name, A.Name
from tblResident as R 
left join tblApartment as A
on R.ApartmentID = A.ID
where R.ApartmentID is null

Second

select R.Name, A.Name
from tblResident as R 
left join tblApartment as A
on R.ApartmentID = A.ID
where R.ApartmentID = null

Table structure

enter image description here

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Thor
  • 9,638
  • 15
  • 62
  • 137

2 Answers2

3

for MySQL:

As per MySQL Documentation on Working with NULL Values:

You cannot use arithmetic comparison operators such as =, <, or <> to test for NULL. Because the result of any arithmetic comparison with NULL is also NULL, you cannot obtain any meaningful results from such comparisons

And hence are the results you experienced.

Examples:

mysql> SELECT 1 = NULL, 1 <> NULL, 1 < NULL, 1 > NULL,
     > 1 is null, null is null, null = null;
+----------+-----------+----------+----------+-----------+--------------+-------------+
| 1 = NULL | 1 <> NULL | 1 < NULL | 1 > NULL | 1 is null | null is null | null = null |
+----------+-----------+----------+----------+-----------+--------------+-------------+
|     NULL |      NULL |     NULL |     NULL |         0 |            1 |        NULL |
+----------+-----------+----------+----------+-----------+--------------+-------------+

I think the same is applicable for all other DB platforms.

Ravinder Reddy
  • 23,692
  • 6
  • 52
  • 82
1


Hi Tony,
Good question
You are checking a null column. Basically null is nothing or empty in a simple english. You cannot use operators to select null values. Operators can be used only to match the column which has a value and not null. In this case, is null fucntion is to be used

Jim Macaulay
  • 4,709
  • 4
  • 28
  • 53