I have the following query:
SELECT SUM(quantity) AS qt FROM stockMove WHERE date_mov >= '2019-04-01' AND date_mov <= '2019-04-30' AND ProductCode = '000807' GROUP BY ProductCode
If a have no movement of this product in this date range, the query returns nothing, but I need that to return 0.
I already try:
SELECT SUM(quantity) AS qt, COALESCE(quantity, 0)
and
SELECT SUM(quantity) AS qt, IFNULL(quantity, 0)
but the query still returns 0 rows.
Is there a way to resolve my issue?
Thanks guys.
Advertisement
Answer
In your case, just remove the GROUP BY
and use COALESCE()
:
SELECT COALESCE(SUM(quantity), 0) AS qt FROM stockMove WHERE date_mov >= '2019-04-01' AND date_mov <= '2019-04-30' AND ProductCode = '000807';
An aggregation query with no GROUP BY
always returns one row, even when no rows match. The returned value is NULL
— which is where the COALESCE()
comes in.
With the GROUP BY
, the query returns no rows at all. Can’t convert nothing into a 0
.