Using NULLs in Compound Queries

We discussed union compatibility conditions at the beginning of this chapter. The union compatibility issue gets interesting when NULLs are involved. As we know, NULL doesn’t have a datatype, and NULL can be used in place of a value of any datatype. If we purposely select NULL as a column value in a component query, Oracle no longer has two datatypes to compare in order to see whether the two component queries are compatible. For character columns, this is no problem. For example:

            SELECT 1 NUM, 'DEFINITE' STRING FROM DUAL
            UNION
            SELECT 2 NUM, NULL STRING FROM DUAL;

       NUM STRING
---------- --------
         1 DEFINITE
         2

Notice that Oracle considers the character string ‘DEFINITE’ from the first component query to be compatible with the NULL value supplied for the corresponding column in the second component qery. However, if a NUMBER or a DATE column of a component query is set to NULL, we must explicitly tell Oracle what “flavor” of NULL to use. Otherwise, we’ll encounter errors. For example:

            SELECT 1 NUM, 'DEFINITE' STRING FROM DUAL
            UNION
            SELECT NULL NUM, 'UNKNOWN' STRING FROM DUAL;

SELECT 1 NUM, 'DEFINITE' STRING FROM DUAL
       *
ERROR at line 1:
ORA-01790: expression must have same datatype as corresponding expression

Note that the use of NULL in the second component query causes a datatype mismatch between the first column of the first component query, and the first column of the second component query. Using NULL for a DATE column causes the same problem, ...

Get Mastering Oracle SQL now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.