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;
$$;
Craig Ringer
  • 307,061
  • 76
  • 688
  • 778
user962449
  • 3,743
  • 9
  • 38
  • 53
  • 2
    You don't need the loop, this can be done (much more efficiently) with a single update statement. –  Jan 14 '14 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. – Craig Ringer Jan 15 '14 at 02:31

1 Answers1

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?

Community
  • 1
  • 1
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228