How to use PostgreSQL functions
· Category: SQL & Databases
Short answer
PostgreSQL functions encapsulate reusable logic using SQL, PL/pgSQL, or other supported languages. They can return scalars, sets, or composite types.
Steps
- Create a SQL function:
CREATE FUNCTION add_one(val INTEGER) RETURNS INTEGER AS $$
SELECT val + 1;
$$ LANGUAGE SQL;
- Create a PL/pgSQL function with variables and control flow.
- Return sets with
RETURNS TABLEorRETURNS SETOF. - Use
IMMUTABLE,STABLE, andVOLATILElabels to help the optimizer. - Drop with
DROP FUNCTION add_one(INTEGER);
Tips
- Use functions to centralize calculation logic and reduce client-side duplication.
- Overloading functions by argument types is supported and useful for polymorphic APIs.
Common issues
- Functions executed inside triggers must be declared carefully to avoid mutating-table errors.
- Heavy use of functions in
WHEREclauses can prevent index usage.r