Search code examples
postgresqlplpgsqlpostgresql-9.3

PL/pgSQL If Exists Display the result without a function


I have a statement here that runs fine from what I can tell. If evaluates the condition and sticks the result into a variable. All I need to know is how to read the value out of the variable and display it. Thanks

DO
$do$
DECLARE result text;

BEGIN
IF EXISTS (select 1 from siteName where SiteNameID=9) THEN
   SELECT 'Yes' into result;
ELSE 
   SELECT 'No' into result;
END IF;

END
$do$

Solution

  • You cannot return data from a DO command. For that, you would need a function. With DO commands you are restricted to messages from RAISE like Denis provided, or you can write data to tables or temp tables, and select from them.

    DO
    $do$
    BEGIN
    CREATE TEMP TABLE site9_exists AS
    SELECT EXISTS (SELECT 1 FROM sitename WHERE sitenameid=9) AS result;
    END
    $do$;
    
    SELECT result FROM site9_exists;
    

    Of course, you wouldn't need the DO command at all for the trivial example ...