PostgreSQL: How to create a pairing function? -


how create user defined function in postgresql acts c function pair defined below?

also, type of function should use , why?

(a) query language (sql) function
(b) procedural language function
(c) internal function
(d) c-language function
(e) none of above

bonus points implementations in both sql & pl/pgsql languages.

#include <stdio.h> #include <math.h>  int pair(int x, int y) {     int z;     if (x < y) {         z = x * (y-1);         y = y - x - 2;     } else {         z = (x-1) * y;         y = x - y - 2;     }     return z + pow(y, 2) / 4; }  // testing  void test(int x, int y, int z) {     printf("%s", pair(x, y) == z ? "." : "f"); }  int main(void) {     test(1, 2, 1);     test(1, 3, 2);     test(1, 4, 3);     test(1, 5, 5);     test(1, 6, 7);     test(1, 7, 10);     test(1, 8, 13);     test(1, 9, 17);      test(2, 3, 4);     test(2, 4, 6);     test(2, 5, 8);     test(2, 6, 11);     test(2, 7, 14);     test(2, 8, 18);     test(2, 9, 22);      printf("\n");      return 0; } 

use sql case statement:

case when x < y    x * (y - 1) + ((y - x - 2)^2)::int / 4 else    (x - 1) * y + ((x - y - 2)^2)::int / 4 end 

the operator ^ function power() return double precision. cast int match question.

wrapped plain sql function (with operator ^):

create or replace function pair1(x int, y int)   returns int $func$ select case when x < y           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 have tro reference input columns positional parameters $1, $2 instead.

the same pl/pgsql function (with function power()):

create or replace function pair2(x int, y int)   returns int $func$ begin return case when x < y           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; 

sql fiddle demo.

i depends, use simple sql function. , don't forget declare immutable. allows various performance optimizations in bigger queries , using in functional indexes. example more details:
does postgresql support "accent insensitive" collations?


Comments