Sub topic 5
NULL inputs and STRICT
This chapter covers how SQL functions in PostgreSQL behave when an argument is NULL. It also covers the STRICT marker, which changes that behavior, and the problems it can cause. It assumes you can write a basic CREATE FUNCTION ... LANGUAGE sql statement, you know that NULL means "unknown or missing value", and you have seen parameters and return values from earlier chapters.
Why NULL needs attention in functions
In SQL, almost any operation on NULL produces NULL. NULL + 1 is NULL, and 'a' || NULL is NULL. A function body is ordinary SQL, so it inherits this behavior. Consider the full_name function from the previous chapter:
SELECT 'Ada' || ' ' || NULL;The result is NULL, not 'Ada '. If the function body does nothing special, a NULL argument usually flows through the expression and produces a NULL result. Sometimes it produces a surprising result instead, such as a comparison that is never true.
PostgreSQL gives you two levels of control:
- Handle NULL inside the body with expressions such as
COALESCE,NULLIF, andIS NULL. - Declare the function STRICT so that PostgreSQL handles NULL inputs for you.
Default behavior: CALLED ON NULL INPUT
Every function has a NULL-input mode. The default is CALLED ON NULL INPUT. The function runs normally even when some or all arguments are NULL, and the body decides what to do.
CREATE FUNCTION label_price(price numeric)
RETURNS text
LANGUAGE sql
IMMUTABLE
AS $$
SELECT CASE
WHEN price IS NULL THEN 'unknown'
WHEN price > 100 THEN 'expensive'
ELSE 'affordable'
END;
$$;
SELECT label_price(250), label_price(NULL);The first call returns expensive. The second returns unknown, because the body tests price IS NULL explicitly. This is only possible because the function was allowed to run with a NULL argument.
STRICT: skip the call when any argument is NULL
A function declared STRICT is not run at all if any argument is NULL. PostgreSQL returns NULL immediately. RETURNS NULL ON NULL INPUT is an equivalent spelling.
CREATE FUNCTION full_name(first_name text, last_name text)
RETURNS text
LANGUAGE sql
IMMUTABLE STRICT
BEGIN ATOMIC
SELECT first_name || ' ' || last_name;
END;
SELECT full_name('Ada', 'Lovelace');
SELECT full_name('Ada', NULL);The first call returns Ada Lovelace. The second returns NULL without executing the body. The BEGIN ATOMIC form needs PostgreSQL 14 or later.
The following table compares the two modes.
| Aspect | CALLED ON NULL INPUT (default) | STRICT |
|---|---|---|
| Body runs when an argument is NULL | Yes | No |
| Result when an argument is NULL | Whatever the body computes | Always NULL |
| Body needs its own NULL checks | Yes, if NULL matters | No |
| Can return a non-NULL value for NULL input | Yes | No |
Why STRICT is useful
STRICT has three practical benefits.
- Less code. You do not write
IForCASElogic just to propagate NULL. - Clear contract. Readers see immediately that NULL in means NULL out.
- Better planning. A strict function that is also
IMMUTABLEcan be evaluated at plan time for constant arguments, and the planner knows that a NULL input cannot produce a non-NULL output. This also matters for inlining, covered in a later chapter.
What STRICT does not do
STRICT only looks at the arguments the caller passes. It does not check NULLs that appear inside the body, such as values read from a table. If the body runs SELECT balance FROM accounts WHERE id = p_account and the balance column is NULL, the function returns NULL even though the argument was not.
Which arguments count
The rule is "any argument is NULL", not "all arguments are NULL". With two parameters, one NULL is enough to skip the call.
CREATE FUNCTION add_tax(price numeric, rate numeric DEFAULT 0.20)
RETURNS numeric
LANGUAGE sql
IMMUTABLE STRICT
AS $$
SELECT price * (1 + rate);
$$;
SELECT add_tax(100);
SELECT add_tax(100, NULL);
SELECT add_tax(NULL);add_tax(100)uses the default rate and returns120.00.add_tax(100, NULL)passes NULL explicitly. The default is not used, because a default applies only when the argument is omitted. The function is skipped and the result is NULL.add_tax(NULL)returns NULL, becausepriceis NULL.
This is a common source of confusion. Omitting an argument and passing NULL are different things.
Handling NULL yourself
Sometimes NULL should not produce NULL. A display name might fall back to a placeholder, or a missing rate might mean "no tax". In those cases leave the function in the default mode and use COALESCE, which returns its first non-NULL argument.
CREATE FUNCTION safe_full_name(first_name text, last_name text)
RETURNS text
LANGUAGE sql
IMMUTABLE
AS $$
SELECT trim(concat_ws(' ', first_name, last_name));
$$;
SELECT safe_full_name('Ada', NULL);
SELECT safe_full_name(NULL, NULL);concat_ws skips NULL arguments, so the first call returns Ada. The second call returns an empty string, not NULL. If you wanted NULL there, wrap the result in NULLIF(..., '').
Useful tools for NULL handling inside a body:
COALESCE(x, default)replaces NULL with a fallback.NULLIF(x, y)returns NULL whenx = y, which turns sentinel values such as empty strings into NULL.x IS NULLandx IS NOT NULLtest for NULL. Never writex = NULL, which yields NULL and is never true.x IS DISTINCT FROM ycompares two values and treats NULLs as ordinary, comparable values.
Common errors
Marking a function STRICT when NULL is meaningful
A function that is supposed to turn NULL into something else will never run its logic if it is strict.
CREATE FUNCTION price_or_zero(price numeric)
RETURNS numeric
LANGUAGE sql
IMMUTABLE STRICT
AS $$
SELECT COALESCE(price, 0);
$$;
SELECT price_or_zero(NULL);This returns NULL, not 0. The COALESCE never executes, because the function is skipped. Remove STRICT to get the intended behavior.
Using STRICT with a function that returns rows
For a set-returning function, a strict function called with a NULL argument returns zero rows, not one NULL row. The following function shows this:
-- Assumes a table orders(id int, customer_id int, ordered_at timestamptz, total numeric)
CREATE FUNCTION customer_orders(p_customer_id int)
RETURNS SETOF orders
LANGUAGE sql
STABLE STRICT
AS $$
SELECT * FROM orders WHERE customer_id = p_customer_id;
$$;
SELECT * FROM customer_orders(NULL);The query returns an empty result. That is usually what you want, but be aware that the caller cannot tell "no orders" from "NULL argument".
Expecting STRICT to protect default parameters
As shown above, STRICT applies to the final argument list, after defaults are filled in. An explicit NULL overrides a default and triggers the strict behavior.
Forgetting that the default is not strict
Many built-in functions are strict, so it is easy to assume yours are too. A user-defined function is not strict unless you say so. If you rely on NULL propagating but forget the keyword, the body runs with NULL inputs, and the result depends on the expressions inside it. A call such as price * (1 + rate) still gives NULL, but a function containing COALESCE or CASE may not.
Checking and changing the setting
The proisstrict column of the pg_proc catalog records whether a function is strict.
SELECT proname, proisstrict
FROM pg_proc
WHERE proname IN ('add_tax', 'safe_full_name', 'full_name');You can change the mode without rewriting the function:
ALTER FUNCTION add_tax(numeric, numeric) CALLED ON NULL INPUT;
ALTER FUNCTION add_tax(numeric, numeric) STRICT;How STRICT affects inlining and indexes
PostgreSQL can replace a simple SQL function call with its body, a step called inlining. For a scalar SQL function, inlining is blocked in one case that involves this chapter's topic. If a function is STRICT and its body might return a non-NULL value for a NULL input, PostgreSQL cannot be sure the inlined expression behaves the same as the function call. In that situation it keeps the function call. This is a performance concern only, since results stay correct. Write strict functions whose bodies naturally return NULL for NULL input, as full_name does, and they remain inlinable.
Similarly, expression indexes on strict immutable functions work well because the planner can reason about NULL handling. Chapters on volatility and inlining cover both points in detail.
Choosing between the two modes
Use STRICT when:
- NULL input has no sensible answer, and NULL output is the natural result.
- The body is pure computation on its arguments, such as arithmetic or string formatting.
- You want the function to be easy to inline and to use in expression indexes.
Use the default mode when:
- The function should substitute a value for NULL.
- A NULL argument has a special meaning, such as "no filter" in a search function.
- You need to distinguish NULL from other values, for example with
IS DISTINCT FROM.
Summary of rules
- Default mode runs the body for every call.
STRICTskips the body and returns NULL when any argument is NULL. - An explicit NULL overrides a default parameter value.
STRICTchecks arguments only, not values read inside the body.- Strict set-returning functions return no rows for NULL input.
- Use
COALESCE,NULLIF,IS NULLandIS DISTINCT FROMwhen NULL needs real handling.
Exercise
The function below is declared STRICT. What does SELECT discount_label(NULL); return, and how would you change the function so it returns 'none'?
CREATE FUNCTION discount_label(pct numeric)
RETURNS text
LANGUAGE sql
IMMUTABLE STRICT
AS $$
SELECT COALESCE(pct::text || '%', 'none');
$$;
Show answer
It returns NULL. Because the function is STRICT and the argument is NULL, PostgreSQL skips the body, so COALESCE never runs. To get 'none', remove STRICT (or run ALTER FUNCTION discount_label(numeric) CALLED ON NULL INPUT). The body then runs with pct as NULL, pct::text || '%' is NULL, and COALESCE returns 'none'.
Exercise
Given add_tax(price numeric, rate numeric DEFAULT 0.20) declared STRICT, what do add_tax(50) and add_tax(50, NULL) return, and why do they differ?
Show answer
add_tax(50) returns 60.00, because the omitted argument takes the default 0.20. add_tax(50, NULL) returns NULL, because the caller passed NULL explicitly. The default applies only to omitted arguments, so the function sees a NULL argument and, being STRICT, skips the body.