📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PostgreSQL Essentials Stored Functions

Stored Functions

6 min read
Stored functions are named reusable code blocks saved in the database. They accept parameters and return values. Functions reduce repeated logic and let applications call complex operations with a single function call.

Writing Functions

CREATE OR REPLACE FUNCTION get_user_orders(uid INTEGER)
RETURNS TABLE(id INT, total NUMERIC) AS $$
  SELECT id, total FROM orders WHERE user_id = uid;
$$ LANGUAGE sql;

-- Call it
SELECT * FROM get_user_orders(1);

Functions encapsulate logic server-side, reducing round-trips.