4

I try to do the the following query with mysql (Should add more conditions, but simplified it for the question, so the sub-query sometimes return null and sometimes return value, this is just for making the query shorter for the question):

SELECT COUNT(*)
FROM table
WHERE date = (SELECT MAX(date) FROM table)

My problem is that if the sub-query return null, my result will be 0, which is not the desired result. Since I can't do IS instead of =, I'm wondering if there is a simple solution.

2
  • 1
    What is your desired result? Commented Dec 17, 2016 at 21:48
  • That will count all rows with null date Commented Dec 17, 2016 at 21:50

4 Answers 4

6

MySQL provides a NULL safe equality comparison <=> (spaceship) operator.

I suspect that if you replace the = equality comparison operator with the NULL safe equality comparison operator, the query will return the results it looks like you are after.


This expression:

  a <=> b

is basically shorthand equivalent for:

  a = b OR ( a IS NULL AND b IS NULL )
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Wasn't aware of this operator!
0

To count all the rows with null date this should work:

SELECT COUNT(*) FROM table WHERE date IS NULL;

1 Comment

This is not what I'm looking for... maybe I wasn't clear. The Date might be with values, and might be null. If there is only null values, then I want it to count how much there are, and if not, the subequry does the trick
0

This should not be a concern.

The subquery only returns NULL if there are no rows or if date is NULL in all rows.

The query will return 0 in this case. That makes sense to me. What would you want it to return?

2 Comments

The query is actually have more conditions.. (like, id and others..), so the subquery will return results sometimes, and sometimes it will return null. Is is make more sense now?
@OferP . . . No, not at all. It is only possible to answer the question that you have asked, not the one that you think it should be. I would suggest that you ask another question with sample data and desired results.
0

You can make a union of both results and calculate the max:

SELECT MAX(datecount) FROM
(SELECT COUNT(*) AS datecount FROM table WHERE date IS NULL 
UNION ALL
SELECT COUNT(*) AS datecount FROM table WHERE date = (SELECT MAX(date) FROM table)) AS derivedtable

1 Comment

I've got an answer already but just for the record, this won't work since the second query might return result, so I don't want the first query results. (Even if it is bigger number).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.