1

I am using Postgres 12.6 in a Java7 application using a hibernate Native query.

I am trying to construct a SQL statement that reads results from a table journalheader where it receives one parameter. The parameter values can be 'Matched' or 'Unmatched'.

The following solution would be inadequate, because it does not cater for null values:

select * from journalheader where matched_status = ?1;

The table does have some rows with the matched_status column of null. I would like these rows to be part of the 'Unmatched' filter.

i.e.

  • If the parameter (?1) is 'Matched', then it will only return rows where matched_status = 'Matched'.
  • If the parameter (?1) is 'Unmatched', then it will only return rows where matched_status = 'Unmatched' or null.

Question

How do I also check for the null values?

Possible solutions

I think I may need to add a check on the parameter value, and if it is 'Unmatched' include or matched_status is null in the statement. I am just not sure how to check the value of the parameter in the sql statement.

select * from journalheader where matched_status = ?1 or <if ?1 equals 'Unmatched'> matched_status is null;
2
  • So the "Unmatched filter" would result in passing null as ?1? Commented May 20, 2022 at 8:05
  • @a_horse_with_no_name, yes that's kind of correct. If the parameter is 'Unmatched', it would need to filter on the table where matched_status values are either 'Unmatched' or null. Commented May 20, 2022 at 8:07

2 Answers 2

1

You can use the keyword COALESCE

select * from journalheader where COALESCE(matched_status, 'Unmatched') = ?1;

This mean use the value of matched_status unless the value is null, if the value is null then use the value Unmatched

Sign up to request clarification or add additional context in comments.

Comments

1

You could try using COALESCE:

select * 
from journalheader 
where matched_status = COALESCE(?1,'Unmatched') 

Or CASE WHEN:

select * 
from journalheader 
where matched_status =CASE WHEN ?1 is null THEN 'Unmatched' ELSE ?1 END  

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.