typestar

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

  1. tax_rate NUMERIC DEFAULT 0.08 makes the second argument optional.
  2. with_tax(100.00) takes the default; adding 0.20 overrides it positionally.
  3. amount => 100.00 is named notation — order stops mattering.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 4 in Functions, step 2 of 23 in PostgreSQL Stored Procedures.

← Previous Next →

Defaults and named arguments in other languages