Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test an if statement in PostgreSQL?

Question: I want to test an if statement in PostgreSQL:

IF (SELECT COUNT(*) FROM pg_language WHERE lanname = 'plpgsql') > 0 THEN
    PRINT 'Good'
ELSE
    PRINT 'Bad'
END IF;

Now this throws an error at IF.

As far as I have read, this is because I need to use plpgsql to be able to use if, print, and variables.

So far, I probably also have to use SELECT instead of print as well.

How can I switch the language before executing this statement to plpgsql ?

I want to test it first, BEFORE I put it in a stored procedure. To test code with variables etc.


Edit:

Solved by:

DO LANGUAGE plpgsql $$
    BEGIN
        IF (SELECT COUNT(*) FROM pg_language WHERE lanname = 'plpgsql') > 0 THEN 
            RAISE NOTICE 'GOOD';
        ELSE
            RAISE NOTICE 'BAD';
        END IF;
    END;
$$;
like image 706
Stefan Steiger Avatar asked Feb 05 '12 18:02

Stefan Steiger


People also ask

Can you use if statements in PostgreSQL?

PostgreSQL has an IF statement executes `statements` if a condition is true. If the condition evaluates to false, the control is passed to the next statement after the END IF part.

What is do $$ in PostgreSQL?

“lang_name” is simply the name of the procedural language. If the language is not mentioned, PostgreSQL will use the default procedural language, PL/pgSQL. $$ (double quoting) is a PostgreSQL substitute for single quotes to avoid quoting issues inside the BEGIN block.

IS NOT NULL condition in PostgreSQL?

The not-null constraint in PostgreSQL ensures that a column can not contain any null value. This is a column constraint. No name can be defined to create a not-null constraint. This constraint is placed immediately after the data-type of a column.

What is the correct syntax of writing if/then statement in PL pgSQL?

Syntax: IF boolean-expression THEN statements [ ELSIF boolean-expression THEN statements [ ELSIF boolean-expression THEN statements ...]] [ ELSE statements ] END IF; IF-THEN-ELSE statements add to IF-THEN by letting you specify an alternative set of statements that should be executed if the condition is not true.


1 Answers

If you just want to test code snippets without going through all the hassle of building and dropping a function, then you can use DO:

=> do language plpgsql $$
    begin
        -- Yes, I have a table called pancakes in my playpen database.
        if (select count(*) from pancakes) > 0 then
            raise notice 'Got some';
        else
            raise notice 'Got none';
        end if;
    end;
$$;

You'll need 9.0+ to use DO.

like image 72
mu is too short Avatar answered Oct 20 '22 02:10

mu is too short