Use an SQL CASE
statement:
CASE WHEN x < y THEN
x * (y - 1) + ((y - x - 2)^2)::int / 4
ELSE
(x - 1) * y + ((x - y - 2)^2)::int / 4
END
The operator ^
as well as the function power()
return double precision
. So I cast to int
to match your question.
Wrapped into a plain SQL function (with operator ^
):
CREATE OR REPLACE FUNCTION pair1(x int, y int)
RETURNS int AS
$func$
SELECT CASE WHEN x < y THEN
x * (y - 1) + ((y - x - 2)^2)::int / 4
ELSE
(x - 1) * y + ((x - y - 2)^2)::int / 4
END
$func$ LANGUAGE sql IMMUTABLE;
In Postgres 9.1 or older you have tro reference input columns with positional parameters $1
, $2
instead.
The same as PL/pgSQL function (with function power()
):
CREATE OR REPLACE FUNCTION pair2(x int, y int)
RETURNS int AS
$func$
BEGIN
RETURN CASE WHEN x < y THEN
x * (y - 1) + power(y - x - 2, 2)::int / 4
ELSE
(x - 1) * y + power(x - y - 2, 2)::int / 4
END;
END
$func$ LANGUAGE plpgsql IMMUTABLE;
I depends, but generally I would use a simple SQL function. And don't forget to declare it IMMUTABLE
. This allows various performance optimizations in bigger queries and using it in functional indexes. Example with more details:
Does PostgreSQL support "accent insensitive" collations?