Reputation: 5394
PostgreSQL 11.1 With the below sql query, where $1 and $2 are strings and $3 is a timestamp, how can the below query be rewritten so that a null value in $3 allows for every date to be selected (not just null dates).
SELECT lastname, firstname, birthdate FROM patients
WHERE UPPER(lastname) LIKE UPPER($1)||'%' and UPPER(firstname) LIKE UPPER($2)||'%' AND birthdate::date = $3::date
UNION
SELECT lastname, firstname, birthdate FROM appointment_book
WHERE UPPER(lastname) LIKE UPPER($1)||'%' and UPPER(firstname) LIKE UPPER($2)||'$' and birthdate::date = $3::date
That is, if $3 is null, then this should reduce to:
SELECT lastname, firstname, birthdate FROM patients
WHERE UPPER(lastname) LIKE UPPER($1)||'%' and UPPER(firstname) LIKE UPPER($2)||'%'
UNION
SELECT lastname, firstname, birthdate FROM appointment_book
WHERE UPPER(lastname) LIKE UPPER($1)||'%' and UPPER(firstname) LIKE UPPER($2)||'$'
Upvotes: 1
Views: 48
Reputation: 31594
Untested but I think you can handle that with a CASE
expression
SELECT lastname, firstname, birthdate FROM patients p
WHERE UPPER(p.lastname) LIKE UPPER($1)||'%'
AND UPPER(p.firstname) LIKE UPPER($2)||'%'
AND (CASE WHEN $3 IS NULL THEN TRUE
ELSE p.birthdate::date = $3::date
END)
UNION
SELECT lastname, firstname, birthdate FROM appointment_book ab
WHERE UPPER(ab.lastname) LIKE UPPER($1)||'%'
AND UPPER(ab.firstname) LIKE UPPER($2)||'%'
AND (CASE WHEN $3 IS NULL THEN TRUE
ELSE ab.birthdate::date = $3::date
END);
Upvotes: 1