What MySQL returns when we use DISTINCT clause with the column having multiple NULL values?

MySQLMySQLi Database

When we use the DISTINCT clause on a column having multiple NULL values then all the NULL values are treated as same by MySQL.

It means as per the properties of the DISTINCT clause, MySQL will return only one NULL value in the result set and eliminate the others. Consider the example of a table named ‘testing’ which have multiple NULL values in column ‘Lname’.

mysql> Select * from testing;
+------+---------+---------+
| id   | fname   | Lname   |
+------+---------+---------+
|  200 | Raman   | Kumar   |
|  201 | Sahil   | Bhalla  |
|  202 | Gaurav  | NULL    |
|  203 | Aarav   | NULL    |
|  204 | Harshit | Khurana |
|  205 | Rahul   | NULL    |
|  206 | Piyush  | Kohli   |
|  207 | Lovkesh | NULL    |
+-----+---------+----------+
8 rows in set (0.00 sec)

mysql> SELECT DISTINCT Lname from testing;
+---------+
| Lname   |
+---------+
| Kumar   |
| Bhalla  |
| NULL    |
| Khurana |
| Kohli   |
+---------+
5 rows in set (0.00 sec)

From the query above, it can be seen that MySQL returns only one NULL and eliminate the others when we use the DISTINCT clause on the column ‘Lname’ having four NULL values.

raja
Published on 22-Feb-2018 07:16:24
Advertisements