Search code examples
mysqlsqlselectsum

SQL sum select returns null


I want to obtain unread messages count from MySQL database using SELECT SUM operator.

So, my SQL is:

SELECT sum(status_field = 'new') unreadMessagesCount
FROM messages
WHERE 'author_uid' = 'authorUID'

And it returns NULL. Why?

I have items in database and I can select it by (SELECT * FROM messages)


Solution

  • It returns NULL because you are comparing strings, not columns with:

    WHERE 'author_uid' = 'authorUID'
    

    And these two strings are not equal. So, all rows are filtered out. The NULL value is because you have an aggregation query. SUM() returns NULL when there are no rows in such a query.

    I'm not sure what you intend. Perhaps:

    WHERE author_uid = 'authorUID'
    

    However, 'authorUID' seems like a strange value for a uid. You need to put an appropriate value there. If it is a string, enclose it in single quotes. If it is a number, do not use single quotes.