In this section, we will understand the operation of PostgreSQL functions and learn how to use the function.
Like operations in programming languages, user-defined operations in PostgreSQL are plpgsql commands that accept parameters, perform an operation such as a complex calculation, and return the result of this operation as a value.
The return value can be a single scaler value or a result set.
In functions, unlike procedures, call is called as the select function name, not as “select*from view_adi”.
For example, let’s write a function called “sayitoplama” that gives the sum of two numbers entered as parameters.
1 2 3 4 5 6 7 8 9 10 11 12 | create function sayitoplama(sayi1 int,sayi2 int) returns integer language plpgsql as $$ declare sonuc integer; begin sonuc:=sayi1+sayi2; return sonuc; end; $$; |
Let’s talk a little about our function mentioned above.
1 2 3 4 5 6 7 8 9 10 11 12 | create function sayitoplama(sayi1 int,sayi2 int) returns integer language plpgsql as $$ declare sonuc integer; begin sonuc:=sayi1+sayi2; return sonuc; end; $$; |
create function sayitoplama(sayi1 int, sayi2 int): After the create function, we enter the function name and the variable names given in parentheses and the data types of these variables.
returns integer: We write the data type that will be returned as a result of the function.
language plpgsql: We select the language to be used in the function.
declare: In this section, we enter the variable name and data type that we will use in the function.
begin-end: We write the necessary plpgsql commands for the operations to be performed between the begin-end block.
Let’s write a function that converts the values entered in uppercase letters to lowercase letters and the letters containing “ı,ş,ç,ö,ğ,ü” into “i,ş,ö,g,u” respectively.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | CREATE OR REPLACE FUNCTION TR_karakter ( metin VARCHAR(100) ) RETURNS VARCHAR(100) LANGUAGE plpgsql AS $$ DECLARE d2 VARCHAR(100); BEGIN d2 =metin; d2 = LOWER(d2); d2 = REPLACE(d2,'ı','i'); d2 = REPLACE(d2,'ş','s'); d2 = REPLACE(d2,'ç','c'); d2 = REPLACE(d2,'ö','o'); d2 = REPLACE(d2,'ğ','g'); d2 = REPLACE(d2,'ü','u'); return (d2); END |