3

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

GMB
  • 216,147
  • 25
  • 84
  • 135
ashish
  • 239
  • 2
  • 6
  • 13
  • 1
    `DISTINCT`, `UNION` and `GROUP BY` use the same semantics as`is not distinct from` when it comes to NULL equality – Martin Smith Dec 28 '18 at 10:14
  • In SQL Server that would be `int`. I don't know if that is the same in MySql . If you CREATE TABLE AS SELECT what datatype do you get? – Martin Smith Dec 28 '18 at 10:17
  • Does this answer your question? [What is the difference between UNION and UNION ALL?](https://stackoverflow.com/questions/49925/what-is-the-difference-between-union-and-union-all) – philipxy Feb 24 '21 at 13:53

3 Answers3

4

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
GMB
  • 216,147
  • 25
  • 84
  • 135
4

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.

Salman A
  • 262,204
  • 82
  • 430
  • 521
0

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)

Derviş Kayımbaşıoğlu
  • 28,492
  • 4
  • 50
  • 72