Search code examples
postgresqlfunctionstored-proceduresprocedure

PostgreSQLFunction with two select statements


I'm trying to create a PostgreSQL function declaring two variables to return on each one the result of a different query, the query themselves are really simple, and rely on the same select with different conditions:

select count (*) from editions where year >= '2000'

and

select count (*) from editions where year < '2000'

The structure of the table is also simple, there are three rows:

  1. Code (numeric)
  2. Version (character)
  3. Year (integer)

How can I create this function?


Solution

  • This is so basic.. I think you can find many tutorial in Google to create this Function.. And your Year column are Integer so don't treat like String use Single Quote..

    Function totalRecords1()

    CREATE OR REPLACE FUNCTION totalRecords1()
    RETURNS integer AS $total1$
    declare
        total1 integer;
    BEGIN
       SELECT count(*) into total1 
       FROM your_table
       WHERE year >= 2000;
       RETURN total1;
    END;
    $total1$ LANGUAGE plpgsql;
    

    Function totalRecords2()

    CREATE OR REPLACE FUNCTION totalRecords2()
    RETURNS integer AS $total2$
    declare
        total2 integer;
    BEGIN
       SELECT count(*) into total2 
       FROM your_table
       WHERE year < 2000;
       RETURN total2;
    END;
    $total2$ LANGUAGE plpgsql;
    

    And Select Statement

    select totalrecords1(), totalrecords2();
    

    You can see here in DEMO