1

I have a query, in which some parameters can sometimes arrive null, and when these arrive null, I want them to ignore those conditions.

SELECT DISTINCT on (i.empleado) i.id
FROM rrhh.imputacion as i 
  INNER JOIN rrhh.empleado as e ON e.id = i.empleado 
  JOIN commons.persona AS pe ON e.persona_comun = pe.id 
  INNER JOIN rrhh.parte__imputaciones as pi ON pi.imputacion = i.id 
  INNER JOIN rrhh.parte as p ON pi.parte = p.id 
  WHERE i.dia >= '2017-12-04' AND i.dia <= '2017-12-11' and p.borrador = false  AND e.fecha_fin_contrato IS NULL AND e.security_domain_id = 2 
  and i.empleado = 126
ORDER  BY i.empleado, i.dia DESC,i.id

I need if the value of my parameter:

"and i.empleado = 126" <- if the value is NULL, ignore this, and bring all the records, without filtering by i.empleado

I do not see concrete examples for postgres.

Thank you.

2
  • How do you pass this value? Java/C#/Php? Commented Dec 16, 2017 at 10:48
  • java: setParameter("empleado", specifitacion.getEmpleado()) (LONG) Commented Dec 16, 2017 at 10:51

1 Answer 1

3

There are two ways of achieving this

  1. Check the parameter in application code and add the condition only when value is non-null.
  2. Add an OR condition on the value to test its nullability. Something like so:

    and (? is null or i.empleado = ?)
    

    In Java, you'd have to apply the parameter twice in this case. But if you are using Spring's NamedParameterJdbcTemplate, you can get away with setting it only once:

    and (:emp is null or i.empleado = :emp)
    
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.