Member-only story
PostgreSQL Functions: Part Four — Conditionals
Read this article if you want to know PostgreSQL conditionals 🤖
Welcome to part four of my series on PostgreSQL functions. In this article, I will cover conditional expressions. As you probably know, Conditionals are one of the most helpful control structures in programming.
So let’s dive in!
If Then Basics
For the first example, I’ll create a function that takes in a single integer argument and returns true if the integer is greater than ten. Otherwise, the function will return false.
create function is_greater_than_ten(num int)
returns boolean as
$$
begin
if num > 10
then return true;
else
return false;
end if;
end
$$ LANGUAGE plpgsql;
The syntax is pretty intuitive here, especially if you are familiar with other programming languages. There’s not much to unpack!
One interesting thing about functions is that they can be called from inside other functions. We can “wrap” the function above inside another function:
create function wrap_greater_than_ten(num int)
returns boolean as
$$
begin
return is_greater_than_ten(num);
end
$$ LANGUAGE plpgsql;