I created a stored function for fetching data:
CREATE OR REPLACE FUNCTION sold_quantity()
RETURNS TABLE(
invoiceid BIGINT,
itemid BIGINT,
sum_sold_quantity NUMERIC)
AS $$
BEGIN
RETURN QUERY SELECT
invoice_id as invoiceid, item_id as itemid, sum(sold_quantity) as
sum_sold_quantity
FROM
invoice_item
WHERE
status='sold'
GROUP BY
invoice_id, item_id;
END; $$
LANGUAGE 'plpgsql';
How to store this data and using it to update the table below?
UPDATE invoice_item
SET sold_quantity = sum_sold_quantity
where invoice_id=invoiceid
and item_id = itemid;
How can we club these two queries (Select and update) in one stored function and execute to fetch all 500k records with the above three columns and update batch wise (like 10 000 records)
language sqlfunction would be more efficient