title: PostgreSQL: Checking for NEW and OLD in a function for a trigger
body: <p>I want to create a trigger which counts rows and updates a field in an other table. My current solution works for INSERT statements but failes when I DELETE a row.</p>
  <p>My current function:</p>
  <pre><code> CREATE OR REPLACE FUNCTION update_table_count()
  RETURNS trigger AS
  $$
  DECLARE updatecount INT;
    BEGIN
        Select count(*) into updatecount 
          From source_table 
         Where id = new.id;
        Update dest_table set count=updatecount 
         Where id = new.id;
  RETURN NEW;
  END;
  $$
  LANGUAGE 'plpgsql';
  </code></pre>
  <p>The trigger is a pretty basic one, looking like.</p>
  <pre><code>CREATE TRIGGER count_trigger
  AFTER INSERT OR DELETE
  ON source_table
  FOR EACH ROW
  EXECUTE PROCEDURE update_table_count();
  </code></pre>
  <p>When I excute a DELETE statement the following error occurs:</p>
  <blockquote>
  <p>ERROR:  record &quot;new&quot; is not assigned yet</p>
  <p>DETAIL:  The tuple structure of a not-yet-assigned record is indeterminate.</p>
  </blockquote>
  <p>I know one solution could be to create just one set of trigger and function for the DELETE and one for the INSERT statement. But I want to do it a bit more elegant and want to know, if there is a solution to check if NEW or OLD is present in the current context and just implement an IF ELSE block. But I dont know how to check for this context sensitive items.</p>
  <p>Thanks for your help</p>