A single number is a number that appeared only once in the MyNumbers table.
Write an SQL query to report the largest single number. If there is no single number, report null.
The query result format is in the following example.
Example 1:
Input:
MyNumbers table:
+-----+
| num |
+-----+
| 8 |
| 8 |
| 3 |
| 3 |
| 1 |
| 4 |
| 5 |
| 6 |
+-----+
Output:
+-----+
| num |
+-----+
| 6 |
+-----+
Explanation: The single numbers are 1, 4, 5, and 6.
Since 6 is the largest single number, we return it.
My Query :
select ifnull(num,null) as num
from MyNumbers
group by num
having count(num)=1
order by num desc
limit 1;
Why the above query is not returning the null, if there no single numbers
I was expecting to display null for non single number test case,but its showing empty table
4
Answers
count(num) will return
0
for null values. This can be solved by usingcount(*)
:see DBFIDDLE, for a step-by-step solution.
You can’t return a null value if your result set contains no rows since that still requires a row to be returned and a value to operate on.
If you want to return a NULL value in the event of no qualifying rows you could create a union of two sets:
You could also use a case expression to test the number of rows and return a null, this requires that at least some data exists
Some fiddle examples
Okay,
group by num having count(*) = 1
is just fine for that. This is the tricky part:The
having
will filter out all rows that don’t have a count of one. So if there are no numbers with a count of one, there are 0 rows in the result set. That’s not the same as a result with one row ofnull
.An aside: beyond exercise, this is a stupid requirement. It doesn’t make sense to conflate
null
with an empty result set. An empty result set is the correct way to express the lack of matching data. Okay, this is just an exercise, after all.Here is my simple solution. I simply
union
the reults of theselect
onMyNumbers
with a select ofnull
. Now there’s anull
in the result set, and if there’s no other result in the result set, thenull
is the only one to come out of the limit. If there is a number, that’s returned instead.Your query returns no rows when it’s nothing to return. As your original query returns at most a single scalar the simplest way is to make it an expression
select (<original scalar query>) as res
: