deltaforce
deltaforce

Reputation: 85

PostgreSQL: Add condition in where clause using CASE

I am using PostgreSQL 8.2 and I am also new to PostgreSQL.

I have to add one condition in the WHERE clause depending upon specific value (49) of the field (activity.type). Here is my Query:

SELECT activity.*
FROM activity 
LEFT JOIN event_types ON activity.customstatusid = event_types.id, getviewableemployees(3222, NULL) AS report 
WHERE 
( 
    CASE WHEN activity.type = 49 THEN 
    'activity.individualid IN(SELECT individualid from prospects where prospects.individualid = activity.individualid)' 
    ELSE 1 
    END 
)
AND activity.date BETWEEN '2016-10-01' AND '2016-10-06' 
AND activity.type IN (21, 22, 49, 50, 37, 199) 
AND (event_types.status = 1 or event_types.status IS NULL);

When I run above query in the command line access of PGSQL then I get below error:

ERROR:  invalid input syntax for integer: "activity.individualid IN(SELECT individualid from prospects where prospects.individualid = activity.individualid)"

What I am missing here?

Upvotes: 2

Views: 14633

Answers (1)

donkopotamus
donkopotamus

Reputation: 23176

Implement your where clause as:

WHERE (
    activity.type != 49 OR
    activity.individualid IN (
        SELECT individualid from prospects 
        WHERE prospects.individualid = activity.individualid)
)
AND activity.date BETWEEN '2016-10-01' AND '2016-10-06' 
AND activity.type IN (21, 22, 49, 50, 37, 199) 
AND (event_types.status = 1 or event_types.status IS NULL);

The first clause will only be true when either:

  • activity.type != 49; or
  • activity.type == 49 and activity.individualid is found in the subquery.

Upvotes: 5

Related Questions