Why Use Database Functions?
Database functions provide several advantages:- Performance: Execute complex logic directly in the database, reducing network overhead
- Reusability: Share logic across multiple applications
- Security: Control access with function privileges and security definer/invoker
- Data Integrity: Keep business rules close to your data
- API Access: Call functions via Supabase’s auto-generated API
Creating Functions
Functions can be created through the SQL Editor in the Dashboard or via migrations.Simple SQL Function
Function with Parameters
PL/pgSQL Functions
PL/pgSQL is a procedural language that provides more control flow options.Basic PL/pgSQL Function
Function with Conditional Logic
Returning Data from Tables
Functions can query and return data from tables.Return Single Row
Return Multiple Rows
Return Complete Table Rows
Modifying Data
Functions can insert, update, or delete data.Insert Function
Update Function
Real Example: Vector Search
Here’s a real function from the Supabase source that performs vector similarity search:Real Example: Hybrid Search
This function combines full-text search with vector search using reciprocal rank fusion:Security Settings
Security Definer vs Invoker
Function Privileges
Control who can execute functions:Error Handling
Raising Exceptions
Using Assertions
Catching Exceptions
Debugging Functions
Adding Logs
Warning and Error Levels
Performance Tips
Use SQL over PL/pgSQL when possible
Use SQL over PL/pgSQL when possible
SQL functions are often faster as the query planner can inline them.
Set search_path for security
Set search_path for security
Always set
search_path on security definer functions.Return SETOF for table data
Return SETOF for table data
Use
returns setof table_name or returns table(...) for better performance.Use STABLE or IMMUTABLE
Use STABLE or IMMUTABLE
Mark functions as
stable or immutable when applicable for better optimization.Function Volatility
Next Steps
Triggers
Automatically execute functions on table events
Tables
Learn about creating and managing tables
Extensions
Extend PostgreSQL with powerful extensions
API Reference
Call functions from your application
