Here's a streamlined approach to PostgreSQL functions:
Basic Structure
CREATE OR REPLACE FUNCTION function_name(param1 type, param2 type)
RETURNS return_type AS $$
BEGIN
-- Your logic here
RETURN result;
END;
$$ LANGUAGE plpgsql;
Key Concepts
Dollar quotes ($$) mark the function body - cleaner than escaping quotes.
RETURNS defines what comes back - can be a simple type (integer, text) or complex (table, record).
BEGIN/END wrap your logic in PL/pgSQL functions.
Common Patterns
Simple calculation:
CREATE OR REPLACE FUNCTION calculate_tax(amount numeric)
RETURNS numeric AS $$
BEGIN
RETURN amount * 0.08;
END;
$$ LANGUAGE plpgsql;
Conditional logic:
CREATE OR REPLACE FUNCTION get_status(score integer)
RETURNS text AS $$
BEGIN
IF score >= 90 THEN
RETURN 'Excellent';
ELSIF score >= 70 THEN
RETURN 'Good';
ELSE
RETURN 'Needs Improvement';
END IF;
END;
$$ LANGUAGE plpgsql;
Working with queries:
CREATE OR REPLACE FUNCTION get_user_count(min_age integer)
RETURNS integer AS $$
DECLARE
user_count integer;
BEGIN
SELECT COUNT(*) INTO user_count
FROM users
WHERE age >= min_age;
RETURN user_count;
END;
$$ LANGUAGE plpgsql;
Returning multiple rows:
CREATE OR REPLACE FUNCTION get_active_products()
RETURNS TABLE(id integer, name text, price numeric) AS $$
BEGIN
RETURN QUERY
SELECT p.id, p.name, p.price
FROM products p
WHERE p.active = true;
END;
$$ LANGUAGE plpgsql;
Quick Tips
- Use
DECLARE section for variables
INTO captures query results into variables
RETURN QUERY for returning table results
RAISE NOTICE for debugging: RAISE NOTICE 'Value: %', my_variable;
- Call functions with
SELECT function_name(args);
Start with simple calculations, then add conditions, then try queries. Each builds on the previous pattern.