Search code examples
sqlpostgresqlpostgresql-9.6

inverting where clause with function, is it possible?


Currently, I'm making a complex query with parameters that will do searches in related tables, this works perfectly, but if I need to say something like "I want to find people who don't have a certain condition", I need to write the same where clause twice: once with IN and once with NOT IN. Is there a way to avoid this scenario? Something like functionX(select id from tablex): boolean

Currently I got something like this:

   select * from tpatient 
   where 
     (includeparameter1 and TPatient.Id in 
       (select patientid from tdoctorvisit where x ilike parameter1)
     ) 
   or (
        (includeparameter1 = false) and TPatient.Id not in (
       select patientid from tdoctorvisit where x ilike parameter1)
     )

Can this somehow be improved to the query below?

    select * from tpatient where 
  functionX(includeparameter1, TPatient.id, 
    select patientid from tdoctorvisit where x ilike parameter1)

This would make my query's a bit smaller as I got a dozen of those where clauses.


Solution

  • I think you can write:

    WHERE includeparameter1 = TPatient.Id in (select patientid from tdoctorvisit where x ilike parameter1)
    

    Because:

    • includeparameter1 = a
    • TPatient.Id in (...) = b

    So you have the condition:

    WHERE (a = true AND b = true) OR (a = false AND b = false)
    

    This is the same as WHERE a = b