1

I am creating a function that allow me to conditionally update specific columns in a table. However, I get an error indicating that there is a syntax error at or near "IF" when I try to run the following code. I'm a bit new to Postgres so it's quite possible. I can't understand some concept/syntax thing in Postgres. Can someone help me by pointing out the mistake I must be making?

CREATE OR REPLACE FUNCTION profiles.do_something(
        p_id UUID,
        p_condition1 BOOLEAN,
        p_condition2 BOOLEAN,
        p_condition3 BOOLEAN
    ) 
RETURNS void AS $$
BEGIN

    IF p_condition1 IS TRUE THEN
        UPDATE tablename SET column1 = null WHERE member_id = p_id;
    END IF;

    IF p_condition2 IS TRUE THEN
        UPDATE tablename SET column2 = null WHERE member_id = p_id;
    END IF;

    IF p_condition3 IS TRUE THEN
        UPDATE tablename SET column3 = null WHERE member_id = p_id;
    END IF;

END;
$$ LANGUAGE 'sql';

1 Answer 1

1

tl;dr $$ LANGUAGE 'plpgsql'

$$ LANGUAGE 'sql';
            ^^^^^

You're tell it to parse the body of the function as sql. In SQL, begin is a statement which starts a transaction.

create or replace function test1()
returns void
language sql
as $$
-- In SQL, begin starts a transaction.
-- note the ; to end the statement.
begin;
    -- Do some valid SQL.
    select 1;
-- In SQL, end ends the transaction.
end;
$$;

In SQL you wrote begin if ... which is a syntax error.

The language you're using is plpgsql. In plpgsql, begin is a keyword which starts a block.

create or replace function test1()
returns void
language plpgsql
as $$
-- In PL/pgSQL, begin starts a block
-- note the lack of ;
begin
    -- Do some valid SQL.
    select 1;
-- In PL/pgSQL, end ends the block
end;
$$;
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. Although now I'm wondering how this should be written to be a valid SQL function instead of plpgsql. My searches for SQL end up being MS-SQL related which I assume is not the same "sql" as the one in postgres?
@Michael MS-SQL likes to refer to itself as "SQL Server". No, "SQL" refers to the SQL Standard which they theoretically follow. SQL is not a procedural language, so the standard allows different languages for SQL functions. Most define their own. MS-SQL has Transact-SQL, PostgreSQL has PL/pgSQL.
@Michael And yes, you can do this as straight SQL. UPDATE tablename SET column1 = case when p_condition1 then null else column1 end, column2 = case when p_condition2 then null else column2 end, column3 = case when p_condition3 then null else column3 end, WHERE member_id = p_id;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.