Introduction
PostgreSQL is the most popular object-relational database system. It is a robust, high-performance based database system. In addition, is open source and free. In this article, we will discuss how to use procedures and functions to perform operations, like insert, delete, update, and select.
Function
In general, a function is a set of SQL statements that carried out any operation, such as select, insert delete, and update. There are two types of functions in PostgreSQL "system-defined functions" and "user-defined functions". In this article, we discuss the user-defined function.
Syntax
- CREATE OR REPLACE FUNCTION function_name (parameters-list)
- RETURNS return_type
- LANGUAGE plpgsql
- AS
- $$
- DECLARE
-
- BEGIN
-
- END
- $$
Listing 1.
Advantage
You can have multiple SQL statements in a function and you can return any type of results like a table or a single value (integer, varchar, date, timestamp, etc).
Limitation
You can not use transactions inside the function.
Procedure
To overcome the limitations of a function, PostgreSQL has a procedure that supports transactions. In the procedure, we can start, commit, rollback the transaction. However, the procedure can not return a result set like a table. It can only return the INOUT parameters.
Syntax
- CREATE OR REPLACE PROCEDURE procedure_name (parameters-list)
- LANGUAGE plpgsql
- AS
- $$
- DECLARE
-
- BEGIN
-
-
-
- END
- $$
Listing 2.
Create database
To create the database, right-click on the databases and Create a Database, as shown in Figure 1.
Figure 1.
In general, the tab set the name of the database in this demo, In our case, we are using “EmployeeManagementSystem”.
Create table
Let’s create the Employees table in the EmployeeManagementSystem database using the following SQL script as shown in Listing 1.
- CREATE TABLE Employees
- (
- Id serial,
- Name VARCHAR(100),
- DateOfBirth Date,
- City VARCHAR(100),
- Designation VARCHAR(100),
- JoiningDate Date
- )
Listing 3.
Click the “Run” button to execute the above script as shown in figure 3.
Parameters Type
Before creating a procedure and function, let’s discuss the type of the parameters, there are three types of parameters, we can use an in function and procedure:
IN
IN represents an input type parameter. It is used to pass the value in the function or procedure, by default all the parameters are input type if we don’t use IN keyword after the parameter name.
OUT
OUT represents the output type parameters. It returns the value; you can pass it as null or it can be uninitialized because these types of a parameter only use to set and return value from function and procedure
INOUT
INOUT represent both input and output type parameter, these types of parameters can be used to pass the value as well as return the value from a function or procedure.
Create Procedure
Use the below script to create a procedure with the name “AddEmployee”. This will insert the employee information in the employee table.
- CREATE OR REPLACE PROCEDURE AddEmployee
- (
- EmpId INOUT INT,
- EmpName VARCHAR(100),
- EmpDob DATE,
- EmpCity VARCHAR(100),
- EmpDesignation VARCHAR(100),
- EmpJoiningDate DATE
- )
- LANGUAGE plpgsql AS
- $$
- BEGIN
- INSERT INTO Employees (Name,DateOfBirth,City,Designation,JoiningDate) VALUES
- (EmpName,
- EmpDob,
- EmpCity,
- EmpDesignation,
- EmpJoiningDate
- ) RETURNING Id INTO EmpId;
- END
- $$;
Listing 4.
Let’s execute this procedure using the SQL statement as shown in listing 5. It will insert employee records in the employee table.
- CALL AddEmployee(null,'Peter Parker','1997-10-01','New York' ,'Web Developer','2020-11-01')
Listing 5.
Figure 5.
Now check the table to see the inserted record with the help select statement as shown in listing 6.
Listing 6.
Now we will create a procedure to update the employee record as shown in listing 7.
- CREATE OR REPLACE PROCEDURE UpdateEmployee
- (
- EmpId INT,
- EmpName VARCHAR(100),
- EmpDob DATE,
- EmpCity VARCHAR(100),
- EmpDesignation VARCHAR(100),
- EmpJoiningDate DATE
- )
- LANGUAGE plpgsql AS
- $$
- BEGIN
- UPDATE Employees SET
- Name = EmpName,
- DateOfBirth = EmpDob,
- City = EmpCity,
- Designation = EmpDesignation,
- JoiningDate = EmpJoiningDate
- Where Id = EmpId;
- END
- $$;
Listing 7.
Figure 7.
Follow listing 8, to call the UpdateEmployee procedure that will allow to update employee records.
- CALL UpdateEmployee(1,'Peter S Parker','1999-10-01','New York' ,'Web Developer','2020-11-01')
Listing 8.
Figure 8.
We have created procedures for insert and update, now we will create a procedure that will allow us to delete employee records. See Listing 8.
- CREATE OR REPLACE PROCEDURE DeleteEmployee
- (
- EmpId INT
- )
- LANGUAGE plpgsql AS
- $$
- BEGIN
- DELETE FROM Employees WHERE Id = EmpId;
- END
- $$;
Listing 8.
Figure 9.
See listing 9 to call the DeleteEmployee() for employee ID '2'
Listing 9.
Figure 10.
Now it's time to create functions, Create a function GetAllEmployee() that will return all the employees, see listing 10.
- CREATE OR REPLACE FUNCTION GetAllEmployees()
- RETURNS Employees
- LANGUAGE SQL
- AS
- $$
- SELECT * FROM Employees;
- $$;
Listing 10.
Figure11.
The 'Select' statement will be used to run and get the data from GetAllEmployee() function, as shown in Listing 11.
- SELECT * FROM GetAllEmployees()
Listing 11.
Figure12.
The below function, GetemployeeById(), shown in Listing 12, will return a single row for a particular employee ID.
- CREATE OR REPLACE FUNCTION GetEmployeeById(EmpId INT)
- RETURNS Employees
- LANGUAGE SQL
- AS
- $$
- SELECT * FROM Employees WHERE Id = EmpId;
- $$;
Listing 12.
Figure13.
Let's pass the employee Id '3' to get the employee record with the select statement.
- SELECT * FROM GetEmployeeById(3)
Listing 13.
Figure14.
As we know, we are storing the "date of birth" of the employee, So let's create a function the will return the age of the employee, In listing 14, we are using the system defined "Age" function that will take two parameters current date and employee date of birth. It will return the difference as the age of the employee.
- CREATE OR REPLACE FUNCTION GetEmployeeAge(EmpId INT, Age OUT VARCHAR(100))
- LANGUAGE plpgsql
- AS
- $$
- BEGIN
- SELECT AGE(NOW()::Date,DateOfBirth) into Age FROM Employees WHERE Id = EmpId;
- END;
- $$
Listing 14.
Figure15.
Call the GetEmployeeAge() function for employee ID 1 and it will return 21 years, 3 months, 21 days.
- SELECT * FROM GetEmployeeAge(1)
Listing 15.
Figure 16.
Conclusion
A function is a good choice to execute an SQL statement that returns a single value result or table formatted result. However, if you want to start a transaction, commit or rollback with multiple SQL statements, then the procedure is the best choice.