I want to filer data from my postgres database. i want to use where clause together with postgres case expressions for filtering data in a single query. i want some thing like this logic
select *from [my-table-name] where ( CASE
WHEN column1 = 0 THEN condition1
ELSE condition2
END
)
what i want is if my column1 is zero i want to filter those rows with condition1 and if column1 is not zero i want to filter those rows with condition2. if case expression was not used i have to write query like this
select *from [my-table-name] where column1 = 0 and condition1
select *from [my-table-name] where column1 <> 0 and condition2
for getting those required data
i tried writing seperate queries for getting those required data
2
Answers
Using both the WHERE clause and the CASE expression in a single query, you can perform the desired filtering. Here is how to go about it:
The CASE statement in this query checks the column1’s value. If it equals 0, condition 1 is evaluated. If it does not, condition 2 is evaluated. A true or false outcome from the CASE expression will be used as the filter condition in the WHERE clause.
Hope this is helpful.
Using
CASE
expressions inWHERE
clauses can adversely affect query performance because doing so can prevent the execution planner from identifying opportunities to use available indexes. I’ll useEXPLAIN (ANALYZE)
to demonstrate the potential performance difference between usingCASE
expressions and pure conditional logic in theWHERE
clause.The following commands establish the demonstration environment:
The first query uses
CASE
to determine which additional conditional test is applied:Running this query with
EXPLAIN (ANALYZE)
returned the following:The second query is functionally equivalent to the first, but uses pure conditional logic instead of a
CASE
expression:The resulting explain plan shows a total execution time about 1000 times faster than the query using
CASE
(0.088 ms vs. 87.631 ms):