AI Hints
Home›PostgreSQL Tutorial›Functions and Procedures
PostgreSQL · Lesson 73 of 120

SQL Functions

Reusable logic.

⏱ 2 min read▶ Video at 1:05:45🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

The price with tax is needed in many queries. Instead of repeating the formula, put it in a function. Then every query uses the same rule.

  • Same formula
  • Many queries
  • A function

A price with tax

Create function names it, lists the inputs, and the return type. The body is a SQL expression. Immutable tells Postgres the same input always gives the same output. Run it. Prices with twenty percent tax.

query.sqlsql
CREATE FUNCTION with_tax(price numeric, rate numeric DEFAULT 0.20)
RETURNS numeric
LANGUAGE sql IMMUTABLE
RETURN round(price * (1 + rate), 2);

SELECT title, price, with_tax(price) AS with_tax
FROM books
ORDER BY book_id
LIMIT 3;
Output
CREATE FUNCTION
       title        | price | with_tax
--------------------+-------+----------
 The Silent Orchard | 14.99 |    17.99
 Code of the River  | 12.99 |    15.59
 Stars Over Lagos   |  9.99 |    11.99
(3 rows)

Function options

Language SQL is simplest. Immutable, stable and volatile tell the planner how predictable it is. Default values make inputs optional. And functions can return tables too, with returns table.

keyvalue
LANGUAGE sqlsimple
IMMUTABLEsame in, same out
DEFAULToptional inputs
RETURNS TABLEmany rows

Summary

Functions package reusable logic, so every query uses the same rule. Next, PL pg SQL, for logic with steps.

Key takeaways
  • CREATE FUNCTION
  • RETURNS
  • IMMUTABLE
Next up: PL/pgSQL — logic with steps