Currently, I have a scenario to generate a report where I need to apply multiple but optional filters and conditions either separately or at once while retrieving data from particular table. Currently, I am checking each filter and applying it by creating separate SQL statement for each scenario as below:
For instance: Reporting requirements: sort by column x, filter where column y = "foo", date between a and b.
Scenario 1: All filter applied.
SELECT * FROM REPORT_TABLE WHERE y='foo' AND date>a AND date<b ORDER BY x ASC
Scenario 2: Sort and date filter applied.
SELECT * FROM REPORT_TABLE WHERE date>a AND date<b ORDER BY x ASC
Scenario 3: Sort and 'foo' type filter applied.
SELECT * FROM REPORT_TABLE WHERE y='foo' ORDER BY x ASC
Scenario 4: Only sort applied
SELECT * FROM REPORT_TABLE ORDER BY x ASC
//So on...
The problem with above method is that with increasing filters there might be many scenario in order to query table. Therefore, Is there a way to accomplish above operation by simply reusing the query result.
For example, Even If I have single or multiple, check each filter and apply consequently.
Scenario: provide all required filter as list
//first get all the rows and store it variable.
result = SELECT * FROM report_table;
//Now loop through each filter from given filter list and apply it.
//and store the updated query result
result = SELECT * FROM result WHERE //apply filter 1.
//loop end.
//finally all filter applied, return the result.
select * from REPORT_TABLEand add the rest based on the filters? Btw,...WHERE ORDER BY ...doesn't work, you'd need to remove theWHEREhere.