Declare COUNT value as variable (PostgreSQL)
<p>Does anyone know if it possible to declare the COUNT value as a variable to call in queries/functions/triggers?</p>

<p>I would like to use the COUNT value to trigger data transfer from table1 to table2, triggering when the row count of table1 reaches 500.</p>

<p>FIX.....</p>

<p>Defining count function:</p>

<pre><code>    CREATE OR REPLACE FUNCTION count_function () RETURNS integer AS $$  
     BEGIN
     RETURN (SELECT COUNT(*) FROM table1);
    END $$ LANGUAGE plpgsql;
</code></pre>

<p>Calling the variable to trigger an event:</p>

<pre><code>    CREATE OR REPLACE FUNCTION save_table2()
    RETURNS trigger AS
    $$
    BEGIN
    IF count_function()&gt;=500 THEN
    INSERT INTO table2
    values ('NEW.column1','NEW.column2');
    END IF;
    RETURN NEW;
    END $$
    LANGUAGE plpgsql;

    CREATE TRIGGER copy_trigger 
    AFTER INSERT ON table1 
    FOR EACH ROW
    EXECUTE PROCEDURE save_table2();
</code></pre>