How null is treated using union and union all in mysql?

Viewed 13740

based on below statement

select null
union
select null

the output of the above statement is:

null

While this statement :

select null
union all
select null

Outputs:

null
null

As null <> null then how the value null is treated here and in which datatype it is considered

3 Answers

In standard SQL, UNION removes duplicate records, UNION ALL does not. Happlily your RDBMS is clever enough to figure out that NULL IS NULL, and eliminates duplicate rows when UNION is used.

NB : null = null is unknown, however null <> null is unknown as well. The only way to check for nullity is to use something like IS NULL.

SELECT case when null <> null then 1 else 0 end;  --> yields : 0
SELECT case when null =  null then 1 else 0 end;  --> yields : 0
SELECT case when null IS null then 1 else 0 end;  --> yields : 1

UNION is a set operator and involves checking for "duplicate rows". The specs define duplicate rows as "not being distinct". An excerpt from SQL-92 specs:

Two values are said to be not distinct if either: both are the null value, or they compare equal according to Subclause 8.2, "<comparison predicate>". Otherwise they are distinct. Two rows (or partial rows) are distinct if at least one of their pairs of respective values is distinct. Otherwise they are not distinct. The result of evaluating whether or not two values or two rows are distinct is never unknown.

(emphasis mine). So, in this example:

select null
union all
select null

the two rows are considered duplicates of each other because the null values in first column are considered not distinct... i.e. same. And by definition UNION returns only one row from a set of duplicate rows.

I am considering that you know the difference between UNION (deduplicates results) and UNION ALL

select 'x' from dual where null is null \\results with x 

In this case null is actually null. Which means union returns correct result (deduplicated)

Related