1

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)||'$' 

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.