I'm trying to do a function with two in parameters year and code from a table to return the count of the given code and year. The table is something like this:
CREATE TABLE orders (
id INT NOT NULL,
code INT NOT NULL,
service_id INT NOT NULL,
status CHARACTER VARYING(50),
creation TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
status_date TIMESTAMP,
created_user INT
);
I was able to return the count with the function below but when I give values to year and code in which there is no count it returns NULL but zero should be returned, how can I do that?:
CREATE OR REPLACE FUNCTION yearly_orders
(year INT, order_cat orders.code%type) RETURNS INT AS $$
DECLARE
total INT DEFAULT 0;
BEGIN
SELECT COUNT(orders.code) INTO total
FROM orders
WHERE status = 'Requested' AND EXTRACT(YEAR FROM creation) = year::INT AND orders.code = order_cat
GROUP BY year, orders.code;
RETURN total;
END;
$$LANGUAGE plpgsql;
The data is something like:
INSERT INTO orders
(id, code, service_id, status, creation, status_date, created_user)
VALUES
(100,2394,558151,'Requested','2019-06-16 11:12','2019-06-18 14:08',1);