Hi team, how can I make the WHERE clause is applied only when an input field is filled with value? The point is, if a user did not enter any ID to the Input1 or Input2 field, the page returns query without any Where conditions. The condition applies only when the Input field is populated. The trick like the below worked in Retool, but I see it’s creating an error with Appsmith. Would you share your thoughts?
SELECT
*
from test_table t
// make the WHERE clause conditional - only when the input_id field is filled
where
( {{ !input_id1.text }} or p.id = {{ input_id1.text}} ) and
( {{ !input_id2.text }} or p.id = {{ input_id2.text}} )
//
Sure this is possible. Since you can write any JavaScript inside the {{ }} you can even have complex if statements. You would have to wrap your code inside an IIFE to use block statements or you could also use ternary expressions Example
For reference, if you wanted to do this in plain SQL you could COALESCE and use an or in the condition if you have a value that can “toggle” or change:
Example:
SELECT
*
FROM
raw_app_data.events
WHERE
COALESCE({{ EvenIdInput.text}}, '') != ''
AND (
{{ EvenIdInput.text}} = events.event_id
)
Thank you for the ideation, dvaun. I like the idea of having ‘true’ as part of the WHERE to make the code multi-purpose. So I will go like this, to process ‘OR’ of multiple input fields.
select
*
from raw_app_data r
where true
{{ EventIdInput.text ? ` and r.id = ${EventIdInput.text}`: ""
}}
{{ UserIdInput.text ? ` and r.user_id = ${UserIdInput.text}`: ""
}}