# Users
| id | name | age |
| ----- | -------- | ---- |
| 1 | Rand | 25 |
| 2 | Mat | 24 |
| 3 | Perrin | 23 |
Given the above table I've been building queries against it in Rails with the basic stuff which works quite well. The real application has about 10 of those fields to query against.
users = User.none
users = users.where(age: params[:age]) if params[:age]
users = users.where(name: params[:name]) if params[:name]
I've always wanted to try to move that into the database and I came up with this function in Postgres
CREATE OR REPLACE FUNCTION filter_users(name character varying, age integer)
RETURNS TABLE(
user_id int,
name character varying,
age integer
)
AS $$
select id as user_id, name, age
from users
where (name IS NULL OR name = $1)
and (age IS NULL OR age = $2)
$$ LANGUAGE SQL;
What I would like to know is whether there is a better way to do these multiple where
queries, where each of them can be null, and should therefore not be used?