0

I am new to postgres and trying to setup a function that returns a bit.

I keep getting the error

Function's final statement must be SELECT or INSERT/UPDATE/DELETE RETURNING.

I understand that

Unless the function is declared to return void, the last statement must be a SELECT, or an INSERT, UPDATE, or DELETE that has a RETURNING clause.

here is the code

CREATE OR REPLACE FUNCTION "f"(...)
  RETURNS bit AS
 DO $$
 Begin
        IF  someStuff
        THEN 
           0; //also tried select 0 //also tried return 0
        ELSE
           1;  //also tried select 1 //also tried return 0
        END IF;
        0; //also tried select 0 //also tried return 0
END $$

Where am I going wrong with the syntax?

0

2 Answers 2

2

There are several errors:

  • the DO is wrong in a function definition
  • you are missing the specification of the language
  • in PL/pgSQL you use return to return the function's result

So your function becomes:

CREATE OR REPLACE FUNCTION f(some_value integer)
  RETURNS bit AS
 $$
 Begin
    IF (some_value = 1)
    THEN 
       return 0; 
    ELSE
       return 1; 
    END IF;
END $$
language plpgsql

But you should use boolean instead of bit to return true/false flags:

CREATE OR REPLACE FUNCTION f(some_value integer)
  RETURNS boolean AS
 $$
 Begin
    IF (some_value = 1)
    THEN 
       return false; 
    ELSE
       return true; 
    END IF;
END $$
language plpgsql
Sign up to request clarification or add additional context in comments.

Comments

1

If you want to use plpgsql then do as in the a_horse's answer but if you don't need plpgsql do in sql:

create or replace function f(some_value integer)
returns boolean as $$

    select some_value = 1;

$$
language sql;

If the function is the one from this question then this will do it:

create or replace function isPersonQualifiedForJob(pid integer, jid)
returns boolean as $$

    select exists (
        select 1
        from
            getskillsforjob(jid) j
            inner join
            getskillsforperson(pid) p on j.skillid = p.skillid
    )

$$
language sql;

Checking for exists is much faster then counting since it is enough to find the first match.

2 Comments

Even better, but I think the obfuscated someStuff "requirement" will turn out to be more complicated.
@a_horse I think I found the someStuff and if so the sql version is still adequate. See update.

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.