Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL - COUNT() NULL Values

Tags:

mysql

This has been racking my head. I've scoured the internet (including this place) and can't find a solution. So as a last resort I was hoping the good people of this forum might be able to help me out.

I have two tables:

TableA
Order_detailsID 
OrderID
TitleID
Return_date

TableB
TitleID
Title_name
Quantity_in_stock

And would like to run a query that shows the remaining 'Quantity_in_stock'.

If the 'Return_date' is set to NULL then it means the item is currently out -- so I have been trying to use the count() function for the NULL values and subtract it from the 'Quantity_in_stock'.

This is the script I have so far:

DELIMITER //
 CREATE PROCEDURE InStock()
BEGIN

Select TableB.TitleID,
TableB.Title_name,
TableB.Quantity_in_stock AS 'Total_Stock',
COUNT(TableA.return_date IS NULL) AS 'Rented_Out',
TableB.Quantity_in_stock - COUNT(TableA.return_date IS NULL) AS 'Remaining Stock'
From TableB
LEFT JOIN TableA
ON TableA.TitleID = TableB.TitleID
GROUP BY TableB.TitleID;

END//

This works if there is one of more of the TitleIDs at NULL, however if there are no values at NULL, then the Count() is still returning a value of 1 when it should be 0.

What am I doing wrong?

like image 875
brent_mused Avatar asked Aug 16 '26 23:08

brent_mused


2 Answers

Instead of:

COUNT(TableA.return_date IS NULL)

use this:

SUM(CASE 
        WHEN TableA.TitleID IS NULL THEN 0
        WHEN TableA.return_date IS NOT NULL THEN 0
        ELSE 1
      END)

The problem with the TableA.return_date IS NULL predicate is that it's true in two completely different situations:

  1. When there is no matching record in TableA
  2. When there is a matching record but TableA.return_date value of this exact record is NULL.

Using the CASE expression you can differentiate between these two cases.

like image 77
Giorgos Betsos Avatar answered Aug 18 '26 13:08

Giorgos Betsos


I will like to mention a simple concept here, just keep counting the rows when that particular column is null.

select count(*) from table_name where column_name is null
like image 38
Danyal Sandeelo Avatar answered Aug 18 '26 14:08

Danyal Sandeelo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!