Skip to main content
PostgreSQL database functions allow you to encapsulate business logic directly in your database. Functions can be written in SQL, PL/pgSQL, or other procedural languages, and can be called from your application code via the Supabase client libraries.

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

Call it with SQL:
Or use the JavaScript client:

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

Query with filters:

Return Complete Table Rows

Modifying Data

Functions can insert, update, or delete data.

Insert Function

Update Function

Here’s a real function from the Supabase source that performs vector similarity search:
This function combines full-text search with vector search using reciprocal rank fusion:

Security Settings

Security Definer vs Invoker

When using security definer, always set search_path to prevent security vulnerabilities.

Function Privileges

Control who can execute functions:
Restrict all new functions by default:

Error Handling

Raising Exceptions

Using Assertions

Catching Exceptions

Debugging Functions

Adding Logs

View logs in Dashboard → Logs → Postgres Logs.

Warning and Error Levels

Performance Tips

SQL functions are often faster as the query planner can inline them.
Always set search_path on security definer functions.
Use returns setof table_name or returns table(...) for better performance.
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