I am trying to implement a code written in mysql to postgres to return true or false existence of tuple, however, I have not been able to do so successfully.
The present code is the one that works without problem in mysql, however, I would like to run it in postgress. How could I implement equivalence
CREATE FUNCTION searchUser(inPhone VARCHAR(13))
RETURNS bool
BEGIN
RETURN (CASE WHEN EXISTS(
SELECT 1
FROM client
WHERE phone=inPhone)
THEN 1 ELSE 0 END );
END//
I have tried to do this in postgres, but it doesn’t work, throwing sitaxix error
CREATE FUNCTION searchUser(inPhone VARCHAR(13))
BEGIN
RETURN CASE WHEN EXISTS
(SELECT 1 FROM client WHERE phone=inPhone)
THEN '1'
ELSE '0';
END;
$$ LANGUAGE plpgsql;
3
Answers
You can also Return
BOOLEAN
with Postgres:Result:
You can even simplify the function further with this:
here is how you can do it:
fiddle demo
For a simple function like this, you don’t need plpgsql. SQL is good enough, faster and can be optimized by the planner.
Or as @Bergi asked, using EXISTS:
And again using the language SQL