Getting Started with PL/pgSQL and Supabase

Blog

Posted by Nuno Marques on 8 Jan 2025

If you’re exploring Supabase for your projects, you might have stumbled across a term like PL/pgSQL. At first glance, it might sound a bit intimidating, but don’t worry—this blog post will introduce you to what PL/pgSQL is, why it’s useful, and how you can leverage it in your Supabase development workflow.


What is PL/pgSQL?

PL/pgSQL (Procedural Language/PostgreSQL) is a procedural programming language specifically designed to work with PostgreSQL databases. It extends SQL, allowing you to write more advanced database operations such as loops, conditional logic, and exception handling. It’s similar to other procedural languages like PL/SQL in Oracle databases.

Think of it as a way to add programming capabilities to your SQL statements, giving you the power to create reusable and efficient database logic directly in your PostgreSQL instance.


Why Should You Care About PL/pgSQL?

Supabase uses PostgreSQL as its underlying database engine. By learning PL/pgSQL, you can:

  • Write Functions: Create stored procedures and user-defined functions to encapsulate logic and reuse it across your application.
  • Optimize Performance: Minimize the back-and-forth between your application and the database by executing complex logic directly in the database.
  • Enhance Security: Control what users can access or modify by wrapping sensitive operations in secure functions.
  • Simplify Code: Replace complex client-side logic with database-side code that’s easier to manage.

How Does PL/pgSQL Work?

PL/pgSQL allows you to write functions and triggers. Here’s a quick breakdown:

1. Functions

Functions are reusable blocks of logic stored in the database. You can call them directly from your application or other SQL queries.

CREATE OR REPLACE FUNCTION greet_user(name TEXT)
RETURNS TEXT AS $$
BEGIN
  RETURN 'Hello, ' || name || '!';
END;
$$ LANGUAGE plpgsql;

You can call this function like so:

SELECT greet_user('John Doe');

2. Triggers

Triggers are event-driven actions executed automatically when a specified database event (like an INSERT, UPDATE, or DELETE) occurs.

For example, a trigger that logs every new user added to the database:

CREATE OR REPLACE FUNCTION log_new_user()
RETURNS TRIGGER AS $$
BEGIN
  INSERT INTO user_logs(user_id, created_at)
  VALUES (NEW.id, NOW());
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER after_user_insert
AFTER INSERT ON users
FOR EACH ROW
EXECUTE FUNCTION log_new_user();

Using PL/pgSQL in Supabase

Supabase makes it incredibly easy to use PL/pgSQL. Here’s how:

Step 1: Open the SQL Editor

Log into your Supabase project and navigate to the SQL Editor. This is where you’ll write and execute your PL/pgSQL code.

Step 2: Write a Function

For example, if you want to calculate the total price of an order (including tax), you can write a PL/pgSQL function:

CREATE OR REPLACE FUNCTION calculate_total(subtotal NUMERIC, tax_rate NUMERIC)
RETURNS NUMERIC AS $$
BEGIN
  RETURN subtotal + (subtotal * tax_rate);
END;
$$ LANGUAGE plpgsql;

You can now call this function from your Supabase client:

const { data, error } = await supabase.rpc('calculate_total', {
  subtotal: 100,
  tax_rate: 0.08
});

Step 3: Automate Actions with Triggers

Automate tasks like sending welcome emails or updating audit logs with PL/pgSQL triggers. These are defined just like in PostgreSQL, and Supabase handles the execution for you.


Best Practices for Using PL/pgSQL

  1. Keep It Simple: Avoid overly complex functions. Break down large logic into smaller, reusable functions.
  2. Test Thoroughly: Test your PL/pgSQL code in a development environment to avoid unexpected behavior in production.
  3. Leverage Supabase Dashboard: Use the SQL Editor and logs in the Supabase dashboard to debug and optimize your functions.

Conclusion

PL/pgSQL is a powerful tool that can significantly enhance your Supabase projects. Whether you’re automating database tasks, simplifying backend logic, or improving performance, learning PL/pgSQL will take your database skills to the next level.

Start small by writing basic functions and gradually explore advanced features like triggers and error handling. With Supabase's support for PostgreSQL, you have everything you need to get started.