Functions in PL/SQL - GeeksforGeeks

05 Apr, 2018
A function can be used as a part of SQL expression i.e. we can use them with select/update/merge commands. One most important characteristic of a function is that unlike procedures, it must return a value.
Syntax to create a function:
CREATE [OR REPLACE] FUNCTION function_name 
[(parameter_name  type [, ...])] 

// this statement  is must for functions 
RETURN return_datatype  
{IS | AS} 

BEGIN 
    // program code

[EXCEPTION
   exception_section;

END [function_name];

Example:
We have to find the total strength of students using functions presentin different sections in a school// first lets create a tablecreate table section(s_id int, s_name varchar(20), strength int );  // Inserting values into tableinsert into section values(1, 'computer science', 20);insert into section values(2, 'portal', 45);insert into section values(3, 'geeksforgeeks', 60);  // Defining functioncreate or replace function totalStrength  // Defining return typereturn integerastotal integer:=0;  begin                          // calculating the sum and storing it in total select sum(strength) into total from section;return total;  // closing functionend totalStrength;  set serveroutput on;  declareanswer integer;  beginanswer:=totalstrength();   dbms_output.put_line('Total strength of students is  ' || answer);  end;Output:Total strength of students is  125
Now, let’s take an example to demonstrate Declaring, Defining and Invoking a simple PL/SQLfunction which will compute and return the reverse of a number.set serveroutput on;declare       a int;    c int;    n int;   rev int:=0;    r int;  // Defining function function reverse_it( x  IN int) return  intasz int;  // function codebegin    n := x;              while (n > 0)    loop        r := mod(n, 10);        rev := (rev * 10) + r;        n := trunc(n / 10);    end loop;          z := rev;    return z;      end  ;    BEGIN     a := 123456789;            c := reverse_it(a);     dbms_output.put_line('the reverse of number is  ' || c);    END;  Output:the reverse of number is  987654321
Lets implement a recursive function to calculate the factorial of a numberRecursive functions example:DECLARE     num int;     answer int;    // Defining function  FUNCTION factorial(x number)  RETURN int   IS     f int;    BEGIN     IF x = 0 THEN        f := 1;     ELSE        f := x * factorial(x - 1);     END IF;  RETURN f;  END;      BEGIN     num := 5;     answer := factorial(num);     dbms_output.put_line(' Factorial of  '|| num || ' is ' || answer);  END;  Output: Factorial of  5 is 120
Exception handling can be done using exception block in functions but exception handling using try-catch block cannot be done.Example:set serveroutput on;  declarea int;b float;myexp exception;  function  sqroot(x int)return float  asanswer float;  begin  if x < 0 thenraise myexp;  // pre-defined sqrt()  to // calculate square root elseanswer := SQRT(x);   end if;return answer;  exceptionwhen myexp thendbms_output.put_line('square of negative number is                       not allowed so returning the same                      number');return x;end;  beginb := sqroot(-2);dbms_output.put_line('the value is '|| b);end;Output:square of negative number is  not allowed so returning the same number
the value is -2


We have to find the total strength of students using functions presentin different sections in a school// first lets create a tablecreate table section(s_id int, s_name varchar(20), strength int );  // Inserting values into tableinsert into section values(1, 'computer science', 20);insert into section values(2, 'portal', 45);insert into section values(3, 'geeksforgeeks', 60);  // Defining functioncreate or replace function totalStrength  // Defining return typereturn integerastotal integer:=0;  begin                          // calculating the sum and storing it in total select sum(strength) into total from section;return total;  // closing functionend totalStrength;  set serveroutput on;  declareanswer integer;  beginanswer:=totalstrength();   dbms_output.put_line('Total strength of students is  ' || answer);  end;Output:Total strength of students is  125

// first lets create a tablecreate table section(s_id int, s_name varchar(20), strength int );  // Inserting values into tableinsert into section values(1, 'computer science', 20);insert into section values(2, 'portal', 45);insert into section values(3, 'geeksforgeeks', 60);  // Defining functioncreate or replace function totalStrength  // Defining return typereturn integerastotal integer:=0;  begin                          // calculating the sum and storing it in total select sum(strength) into total from section;return total;  // closing functionend totalStrength;  set serveroutput on;  declareanswer integer;  beginanswer:=totalstrength();   dbms_output.put_line('Total strength of students is  ' || answer);  end;
Output:
Total strength of students is  125

Now, let’s take an example to demonstrate Declaring, Defining and Invoking a simple PL/SQLfunction which will compute and return the reverse of a number.set serveroutput on;declare       a int;    c int;    n int;   rev int:=0;    r int;  // Defining function function reverse_it( x  IN int) return  intasz int;  // function codebegin    n := x;              while (n > 0)    loop        r := mod(n, 10);        rev := (rev * 10) + r;        n := trunc(n / 10);    end loop;          z := rev;    return z;      end  ;    BEGIN     a := 123456789;            c := reverse_it(a);     dbms_output.put_line('the reverse of number is  ' || c);    END;  Output:the reverse of number is  987654321

set serveroutput on;declare       a int;    c int;    n int;   rev int:=0;    r int;  // Defining function function reverse_it( x  IN int) return  intasz int;  // function codebegin    n := x;              while (n > 0)    loop        r := mod(n, 10);        rev := (rev * 10) + r;        n := trunc(n / 10);    end loop;          z := rev;    return z;      end  ;    BEGIN     a := 123456789;            c := reverse_it(a);     dbms_output.put_line('the reverse of number is  ' || c);    END;  
Output:
the reverse of number is  987654321

Lets implement a recursive function to calculate the factorial of a numberRecursive functions example:DECLARE     num int;     answer int;    // Defining function  FUNCTION factorial(x number)  RETURN int   IS     f int;    BEGIN     IF x = 0 THEN        f := 1;     ELSE        f := x * factorial(x - 1);     END IF;  RETURN f;  END;      BEGIN     num := 5;     answer := factorial(num);     dbms_output.put_line(' Factorial of  '|| num || ' is ' || answer);  END;  Output: Factorial of  5 is 120

DECLARE     num int;     answer int;    // Defining function  FUNCTION factorial(x number)  RETURN int   IS     f int;    BEGIN     IF x = 0 THEN        f := 1;     ELSE        f := x * factorial(x - 1);     END IF;  RETURN f;  END;      BEGIN     num := 5;     answer := factorial(num);     dbms_output.put_line(' Factorial of  '|| num || ' is ' || answer);  END;  
Output:
 Factorial of  5 is 120

Exception handling can be done using exception block in functions but exception handling using try-catch block cannot be done.Example:set serveroutput on;  declarea int;b float;myexp exception;  function  sqroot(x int)return float  asanswer float;  begin  if x < 0 thenraise myexp;  // pre-defined sqrt()  to // calculate square root elseanswer := SQRT(x);   end if;return answer;  exceptionwhen myexp thendbms_output.put_line('square of negative number is                       not allowed so returning the same                      number');return x;end;  beginb := sqroot(-2);dbms_output.put_line('the value is '|| b);end;Output:square of negative number is  not allowed so returning the same number
the value is -2


Example:
set serveroutput on;  declarea int;b float;myexp exception;  function  sqroot(x int)return float  asanswer float;  begin  if x < 0 thenraise myexp;  // pre-defined sqrt()  to // calculate square root elseanswer := SQRT(x);   end if;return answer;  exceptionwhen myexp thendbms_output.put_line('square of negative number is                       not allowed so returning the same                      number');return x;end;  beginb := sqroot(-2);dbms_output.put_line('the value is '|| b);end;
Output:
square of negative number is  not allowed so returning the same number
the value is -2


Advantages:
We can make a single call to the database to run a block of statements thus it improves the performance against running SQL multiple times. This will reduce the number of calls between the database and the application.We can divide the overall work into small modules which becomes quite manageable also enhancing the readability of the code.It promotes reusability.It is secure since the code stays inside the database thus hiding internal database details from the application(user). The user only makes a call to the PL/SQL functions. Hence security and data hiding is ensured.
We can make a single call to the database to run a block of statements thus it improves the performance against running SQL multiple times. This will reduce the number of calls between the database and the application.
We can divide the overall work into small modules which becomes quite manageable also enhancing the readability of the code.
It promotes reusability.
It is secure since the code stays inside the database thus hiding internal database details from the application(user). The user only makes a call to the PL/SQL functions. Hence security and data hiding is ensured.
SQL-PL/SQL
SQL
Technical Scripter
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Interview Questions
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between SQL and NoSQL
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
Difference between DELETE and TRUNCATE
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
MySQL | Regular expressions (Regexp)