Add function parameter to SQL query WHERE clause
If you don't always pass all parameters, create a function with parameter defaults. The basic, simple form would be an SQL function without dynamic SQL:
CREATE OR REPLACE FUNCTION func(_a int = NULL
, _b text = NULL
, _c text = NULL)
RETURNS TABLE(...) AS
$func$
SELECT ... FROM ...
WHERE (speed = $1 OR $1 IS NULL)
AND (stop = $2 OR $2 IS NULL)
...
$func$ LANGUAGE sql;
Now you can call the function with any number of parameters using named notation:
SELECT * FROM func(_c => 'foo', _a => 123); -- no _b, which defaults to NULL
Note, the assignment operator in the call is =>
(or :=
for Postgres 9.4 or older), not =
!
See:
- The forgotten assignment operator “=” and the commonplace “:=”
- Functions with variable number of input parameters
Aside: "string" is not a data type, text
is.
Much more is possible with dynamic SQL with EXECUTE
in a plpgsql function.
More comprehensive answer on SO with complete recipes:
- Test for is null or = value in function