0

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)

2
  • 2
    Unrelated, but: using PL/pgSQL for a simply query is overkill. Using a language sql function would be more efficient Commented Nov 19, 2018 at 13:31
  • please, don't do it - don't write procedures just for wrapping SELECT command. It is significant performance antipattern - use views instread. Commented Nov 20, 2018 at 5:00

1 Answer 1

1

You can use the function directly in the UPDATE statement

UPDATE invoice_item ii
    SET sold_quantity = sq.sum_sold_quantity 
from sold_quantity() as sq
where ii.invoice_id = sq.invoiceid 
  and ii.item_id = sq.itemid;

For just 500.000 rows, I wouldn't bother doing any batching at all. Just update all rows in a single statement.

In fact you don't really need a function to begin with:

UPDATE invoice_item ii
    SET sold_quantity = sq.sum_sold_quantity 
from (
  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;  
) as sq
where ii.invoice_id = sq.invoiceid 
  and ii.item_id = sq.itemid;
Sign up to request clarification or add additional context in comments.

1 Comment

can you please look into this query. stackoverflow.com/questions/53387137/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.