Defaults and named arguments in SQL
A tax function called three ways: by default, by position, and by name.
-- DEFAULT gives a parameter a fallback; => names arguments at the call.
CREATE FUNCTION with_tax(
amount NUMERIC,
tax_rate NUMERIC DEFAULT 0.08
)
RETURNS NUMERIC
LANGUAGE SQL
IMMUTABLE
RETURN round(amount * (1 + tax_rate), 2);
SELECT with_tax(100.00) AS default_rate;
SELECT with_tax(100.00, 0.20) AS positional;
SELECT with_tax(amount => 100.00, tax_rate => 0.05) AS named;
How it works
tax_rate NUMERIC DEFAULT 0.08makes the second argument optional.with_tax(100.00)takes the default; adding0.20overrides it positionally.amount => 100.00is named notation — order stops mattering.
Keywords and builtins used here
ASCREATEDEFAULTFUNCTIONIMMUTABLELANGUAGENUMERICRETURNRETURNSSELECTSQL
The run, in numbers
- Lines
- 13
- Characters to type
- 376
- Tokens
- 78
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 67 seconds.
Step 2 of 4 in Functions, step 2 of 23 in PostgreSQL Stored Procedures.