Custom PostgreSQL Functions and Extensions
Last Updated :
10 Oct, 2024
PostgreSQL is a highly extensible database that allows users to add custom functionality through functions and extensions. Custom functions enable us to encapsulate complex logic and reuse it in queries.
While extensions enhance PostgreSQL’s capabilities by adding new data types and procedural languages. This article will explain how to create custom functions and use extensions to extend PostgreSQL's core functionality.
PostgreSQL Custom Functions
Custom functions in PostgreSQL are user-defined routines that can perform various operations, like calculations, data transformations, or even direct interaction with database tables. These functions can be written in different languages supported by PostgreSQL, including SQL, PL/pgSQL, PL/Python, and PL/Perl.
Syntax:
CREATE [OR REPLACE] FUNCTION function_name (parameter1 data_type, parameter2 data_type, ...)
RETURNS return_data_type AS $$
BEGIN
-- Function logic goes here
RETURN result;
END;
$$ LANGUAGE plpgsql;
key terms
- function_name: The name of the function.
- parameter1, parameter2: The input parameters for the function.
- return_data_type: The type of data returned by the function.
- LANGUAGE: The language in which the function is written.
Example 1: Custom Function in PL/pgSQL
Before utilizing the total_salary
function, ensure that the employees
table exists. Here's how to create the employees
table and populate it with sample data:
Query:
CREATE TABLE employees (
id SERIAL PRIMARY KEY,
name VARCHAR(50),
department VARCHAR(50),
salary NUMERIC
);
INSERT INTO employees (name, department, salary)
VALUES
('Alice', 'HR', 50000),
('Bob', 'IT', 60000),
('Charlie', 'HR', 55000),
('David', 'IT', 65000),
('Eva', 'Finance', 70000);
Output:
id | name | department | salary |
---|
1 | Alice | HR | 50000 |
2 | Bob | IT | 60000 |
3 | Charlie | HR | 55000 |
4 | David | IT | 65000 |
5 | Eva | Finance | 70000 |
Custom Function to Calculate Total Salary
Now, let’s create a custom function that calculates the total salary of employees in a given department. Now we can now call the total_salary function and it should work without errors:
Query:
CREATE OR REPLACE FUNCTION total_salary(dept_name VARCHAR)
RETURNS NUMERIC AS $$
DECLARE
total NUMERIC;
BEGIN
-- Calculate the total salary for the given department
SELECT SUM(salary) INTO total
FROM employees
WHERE department = dept_name;
-- Return the total salary
RETURN total;
END;
$$ LANGUAGE plpgsql;
SELECT total_salary('IT');
Output:
OutputExplanation:
When you run the SELECT total_salary
('IT');
query, it will return the total salary of employees in the 'IT' department, which is the sum of 60,000 and 65,000, giving an output of 125,000.
Example 2: Custom Function in SQL
Custom functions can also be written in plain SQL. Here is a simple function that returns the square of a number. Now use SQL statements to calculate the square of the number.
Query:
CREATE OR REPLACE FUNCTION square(num INTEGER)
RETURNS INTEGER AS $$
SELECT num * num;
$$ LANGUAGE SQL;
SELECT square(5);
Output:
OutputExplanation:
In this example, the square
function is defined using plain SQL to calculate the square of a given number. When we call the function with SELECT square(5);
, it multiplies the input value 5
by itself (5 * 5
), returning the result 25.
PostgreSQL Extensions
PostgreSQL’s extension system allows users to install additional features that are not part of the core database. Extensions can provide new data types, functions, index methods, or even new procedural languages. PostgreSQL comes with several built-in extensions, and you can also create or install third-party extensions.
How to Install an Extension
We can install an extension using the CREATE EXTENSION command. For example, to install the popular hstore extension (used for storing key-value pairs), use the following command:
CREATE EXTENSION hstore;
Popular PostgreSQL Extensions
1. pg_stat_statements
This extension provides a way to track execution statistics of all SQL queries executed by the database. It is helpful for query performance monitoring.
Installation:
CREATE EXTENSION pg_stat_statements;
2. hstore
The hstore extension enables the storage of key-value pairs in a single PostgreSQL column, ideal for semi-structured data.
Installation:
CREATE EXTENSION hstore;
3. PostGIS
A popular extension that adds support for geographic objects, allowing us to run spatial queries.
Installation:
CREATE EXTENSION postgis;
Example 3: Using hstore Extension
The SQL queries provided demonstrate how to create a table utilizing the hstore extension and insert data into it. The hstore data type allows for the storage of key-value pairs, making it ideal for handling semi-structured data.
Step 1: Installation
CREATE EXTENSION hstore;
Step 2: Creation and insertion of table
CREATE TABLE products (
id SERIAL PRIMARY KEY,
name VARCHAR(50),
attributes hstore
);
INSERT INTO products (name, attributes)
VALUES ('Laptop', 'color => "black", weight => "2kg"');
Output:
id | name | attributes |
---|
1 | Laptop | "color" => "black", "weight" => "2kg" |
Step 3: Query the hstore field:
SELECT name, attributes->'color' AS color
FROM products;
Output:
OutputExample 4: Using pg_stat_statements Extension
The pg_stat_statements extension tracks query execution statistics for monitoring performance. Once installed, you can query the statistics like this:
Query:
SELECT query, calls, total_time
FROM pg_stat_statements
ORDER BY total_time DESC
LIMIT 5;
Output:
query | calls | total_time |
---|
SELECT * FROM employees; | 10 | 0.123 |
SELECT total_salary('IT'); | 5 | 0.045 |
INSERT INTO products ...; | 3 | 0.067 |
Explanation:
The output from the query executed against the pg_stat_statements extension provides insights into the performance of SQL queries executed in the database.
Conclusion
Custom functions and extensions make PostgreSQL more flexible and powerful. Functions help us to reuse code, while extensions add new features and tools. Whether we need to perform complex calculations, work with special data types, or improve performance. It a great choice for both developers and database administrators.
Similar Reads
PostgreSQL - COUNT() Function
The COUNT() function in PostgreSQL is an aggregate function used to return the number of rows that match a specified condition in a query. This article will explore the various syntaxes of the COUNT() function and provide practical examples to help you understand its usage in PostgreSQL. SyntaxDepen
2 min read
PostgreSQL - DROP FUNCTION
In PostgreSQL, the DROP FUNCTION statement is essential for removing functions from your database. Let us learn more about the syntax and the detailed examples to ensure you understand how to use this statement effectively. SyntaxDROP FUNCTION [IF EXISTS] function_name(argument_list) [CASCADE | REST
4 min read
PostgreSQL - User Defined Functions
PostgreSQL, one of the most powerful open-source relational database management systems (RDBMS), provides a strong feature set for creating and utilizing user-defined functions (UDFs). By using user-defined functions, we can enhance the modularity, maintainability, and performance of our database ap
5 min read
PostgreSQL - CREATE FUNCTION Statement
PostgreSQL allows developers to create user-defined functions to encapsulate reusable logic, making database operations more efficient and modular. The CREATE FUNCTION statement is used to define a new function, supporting various procedural languages, with plpgsql being the most commonly used in Po
5 min read
PostgreSQL - Index On Expression
When working with databases, optimizing query performance is crucial, especially when dealing with large datasets. One powerful technique in PostgreSQL is leveraging indexes on expressions. This approach allows you to optimize queries that involve expressions, ensuring faster retrieval times and eff
3 min read
Can We Use Contains in PostgreSQL?
While PostgreSQL does not have a direct CONTAINS function like some other databases, it offers powerful alternatives for achieving similar functionality. Through the use of operators such as LIKE, ILIKE, and advanced Full-Text Search (FTS) functions like to_tsvector() and to_tsquery(). PostgreSQL al
4 min read
Monitoring And Managing Cloud SQL For PostgreSQL
Google Cloud Platform offers a fully managed relational database solution called Cloud SQL for PostgreSQL. It frees customers from the burden of managing the intricate underlying infrastructure to deploy, scale, and administer PostgreSQL databases in the cloud. High availability, smooth integration
5 min read
PostgreSQL - FIRST_VALUE() Function
The FIRST_VALUE() function in PostgreSQL is a window function that retrieves the first value within an ordered set of rows, often within a specific partition. This feature is highly useful for data analysis and reporting by allowing targeted access to specific data points. In this article, we will e
5 min read
Comparing MySQL, PostgreSQL, and MongoDB
When choosing a database management system (DBMS) for your application, selecting the right one can be challenging. Popular choices include MySQL, PostgreSQL, and MongoDB. Each of these databases has its strengths and weaknesses. By comparing their features and how they align with our project's need
7 min read
PostgreSQL - Common Table Expression (CTE)
In PostgreSQL, Common Table Expressions (CTEs) are a powerful feature that allows us to define temporary result sets that can be referenced within other SQL statements. This includes statements like SELECT, INSERT, UPDATE, or DELETE. CTEs make complex queries more readable and maintainable by breaki
4 min read