CREATE FUNCTION in SQL
A saved expression the planner can call anywhere a value fits.
-- A function is a saved expression the planner can call anywhere.
CREATE FUNCTION line_total(quantity INTEGER, price NUMERIC)
RETURNS NUMERIC
LANGUAGE SQL
IMMUTABLE
RETURN quantity * price;
SELECT
oi.sku,
line_total(oi.quantity, p.price) AS owed
FROM order_items AS oi
JOIN products AS p ON p.sku = oi.sku
WHERE oi.order_id = 103;
How it works
CREATE FUNCTION line_total(...)declares typed parameters and a return type.LANGUAGE SQLwith a bareRETURNis the modern standard body form.- The query then calls it per row, exactly like a built-in.
Keywords and builtins used here
ASCREATEFROMFUNCTIONIMMUTABLEINTEGERJOINLANGUAGENUMERICONRETURNRETURNSSELECTSQLWHERE
The run, in numbers
- Lines
- 13
- Characters to type
- 332
- Tokens
- 61
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 52 seconds.
Fastest run
- πΊπΈ brendancol43 tpm
Step 1 of 4 in Functions, step 1 of 23 in PostgreSQL Stored Procedures.