PostgreSQL — Functions
Basic Function
CREATE FUNCTION add_numbers(a INTEGER, b INTEGER)
RETURNS INTEGER AS $$
BEGIN
RETURN a + b;
END;
$$ LANGUAGE plpgsql;
-- Call
SELECT add_numbers(5, 3);
Function with Query
CREATE FUNCTION get_user_count()
RETURNS INTEGER AS $$
DECLARE
count INTEGER;
BEGIN
SELECT COUNT(*) INTO count FROM users;
RETURN count;
END;
$$ LANGUAGE plpgsql;
Function with OUT Parameters
CREATE FUNCTION get_user_stats(
OUT user_count INTEGER,
OUT avg_age NUMERIC
) AS $$
BEGIN
SELECT COUNT(*), AVG(age) INTO user_count, avg_age FROM users;
END;
$$ LANGUAGE plpgsql;
Drop Function
DROP FUNCTION add_numbers(INTEGER, INTEGER);
Function Types
| Language | Description |
|---|---|
| plpgsql | PostgreSQL procedural |
| sql | Pure SQL |
| plpython | Python |
| plv8 | JavaScript |
Mini Practice
- Create a function
- Use parameters
- Return values
- Call functions
Up Next
Continue with Procedures — stored procedures.
Related Topics
Frequently Asked Questions about Functions
What is Functions in PostgreSQL?
Functions is a fundamental concept in PostgreSQL. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Functions?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Functions.
Why is Functions important in PostgreSQL?
Functions is essential for PostgreSQL development. Understanding this concept will help you write better code and solve real-world problems more effectively.