Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does a query/subquery return a NULL and when no value at all?

  1. If a query/subquery doesn’t find any matching rows, then it either returns NULL or no value at all, thus not even a NULL value. Based on what criteria does a query/subquery return a NULL and when doesn’t it return any results, not even a NULL value?

  2. Will a scalar subquery always return NULL, when no matching rows are found? I assume most-outer scalar query also returns NULL if no rows are found?

  3. SELECT FirstName, LastName, YEAR(BirthDate)
    FROM Persons
    WHERE YEAR(BirthDate) IN (SELECT YearReleased FROM Albums);
    
    • If the subquery finds no results, is the WHERE clause of the outer query translated into WHERE YEAR(BirthDate) IN (null);?

    • If WHERE clause is translated into WHERE YEAR(BirthDate) IN(); instead, shouldn’t that be an error condition, since how can YEAR(BirthDate) value be compared to nothing?

like image 226
AspOnMyNet Avatar asked Dec 28 '22 18:12

AspOnMyNet


2 Answers

The subquery would only ever return NULL when YearReleased was NULL, otherwise there would be an empty recordset, making it the IN () case you mentioned.

It's very important to distinguish between the two as they mean entirely different things. NULL indicates that there was something to be SELECTed, although that value indicates a "lack of value" so to speak. An empty recordset indicates that there was nothing to be selected that matched the criteria specified.

EDIT: updated to show example results

alt text

First two queries are just to show what's in the two tables. Third query is your query and the fourth query just shows that it produces an equivalent result (no rows) if you replace the subquery with a NULL. Last query is just to show that the subquery itself just returns a big list of NULLs.

like image 168
Daniel DiPaolo Avatar answered Mar 05 '23 16:03

Daniel DiPaolo


a. If there are no matching rows, then the result set will always be empty. There isn't any special handling for the NULL value.

b. That's not true. If there are no matching rows, then the result set is always empty by definition. The result of a scalar function is not a result set so it will either be NULL or another value.

c.1. If the subquery doesn't return any rows then the "IN" expression will always return false. The set will not be NULL.

c.2. It is valid to compare YEAR(BirthDate) with an empty set. It will just always return false.

like image 26
David Avatar answered Mar 05 '23 16:03

David