0

How come this is not working? Basically, this proc will update columns in the main buyer table to check if the user has data in other tables.

DO language plpgsql $$
    DECLARE 
    buyer integer;
    BEGIN
    FOR buyer IN SELECT id FROM buyers
    LOOP
      IF (SELECT count(*) FROM invoice WHERE buyer_id = buyer) > 0 THEN
        UPDATE buyers SET has_invoice = true WHERE id = buyer;
      ELSE
        UPDATE buyers SET has_invoice = false WHERE id = buyer;
      END IF;
    END LOOP;
    RETURN;
    END;
$$;
2
  • 2
    You don't need the loop, this can be done (much more efficiently) with a single update statement. Commented Jan 14, 2014 at 19:26
  • Also, if you run this while another connection is updating the invoice table, it can produce wrong results. You need to think about concurrency, or take a table lock so you can ignore it. Commented Jan 15, 2014 at 2:31

1 Answer 1

1

It is unclear what is "not working". Either way, use this equivalent UPDATE statement instead:

UPDATE buyers b
SET    has_invoice = EXISTS (SELECT 1 id FROM invoice WHERE buyer_id = b.id);

If you don't need redundant storage for performance, you can use a VIEW or generated column for the same purpose. Then the column has_invoice is calculated on the fly and always up to date. Instructions in this closely related answer:
Store common query as column?

Sign up to request clarification or add additional context in comments.

Comments

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.