In my app I have a list that can be filtered by selecting subcategory
badge. User is able to select a badge
and show only the items from the particular subcategory. But I would like the app to display all items if no subcategory
is selected. The list of selected subcategories is dynamic and injected into an SQL query (see the example below). But when the list is empty, then of course, query doesn’t return any results. How to write a condition that if ANY
list of items is empty
then the query should return all elements of the table?
SELECT *
FROM table
WHERE column = ANY( {{ $state.categoriesBadge.filter((item) => item.isSelected == true).map((item) => item.value) }})
2
Answers
You can try the below query to achieve your desired result:
Explanation of above snippet:
ANY
clause as before to filter the results by the selected subcategories.(1=1)
, which will return all elements of the table.You could use conditional expressions that notice the resulting array is empty and react accordingly: demo
If the array isn’t empty, this is equal to what you already had;
nullif
andcoalesce
won’t do anything.If it’s empty,
nullif
turns it into anull
which in turn makescoalesce
skip it and replace with thecolumn
value, resulting in a self-comparisoncolumn=any(column)
.Note that if the value of
column
isnull
, it will never matchany
and will never be returned – even if you specifically try to target it by supplying anull
in the array. That’s becauseany
uses regular=
comparison against every element of the array andnull=null
isnull
, nottrue
.To be able to search and match
null
, you’ll needarray_position() is not null
, which usesis not distinct from
comparison instead: demo