Set a value to a variable based on the results of a query (in PL/pgSQL style)

38,456

Solution 1

I think what you are looking for is:

cnt := COUNT(*) FROM t;

Solution 2

you can use SELECT INTO

DECLARE cnt INTEGER;
SELECT INTO cnt count(*) FROM t;
Share:
38,456
Oto Shavadze
Author by

Oto Shavadze

Updated on September 06, 2020

Comments

  • Oto Shavadze
    Oto Shavadze over 3 years

    What I need to do is set a value to a variable using the EXECUTING query.

    In pure SQL style, I could do something like the following:

    // here declaring function and etc...
    DECLARE cnt INTEGER;
    
    EXECUTE 'SELECT COUNT(*) FROM t' INTO cnt;
    

    How to achieve the same functionality in the form of a PL/pgSQL function? What is the correct syntax for the following pseudo-code? (The following is obviously the wrong syntax)

    cnt :=  EXECUTE ( 'SELECT COUNT(*) FROM t' )   ;