I have a customer table having following colums – customerId-primary key, customer_name, food_preference, country, wallet_balance.
The requirement is to get all customer data with –
food_preference is vegetarian
country is"USA"
wallet_balance greater than 5000
So in the CustomerRepo in my Spring boot project the method I have written is
@Query(select * from customer where food_preference = ?1 and country = ?2 and walletBalance
?3, nativeQuery = true)
List<CustomerEntity> getCustomersOnCriteria(Stirng foodPreference, String country, long
walletBalance);
Now here the value of country could be null, In that case I would like to have all customers with all countries present in the db with condition wallet balance more than 5000, foodPreference equals Vegetarian. What modification I’ll have to do it in the Query? I am using Postgres db.
2
Answers
Something like this?
The simple solution is to add the
null
possibility in anOR
condition:Though this can lead to a suboptimal execution plan, specially in the case where the query with the country should lead to an index access while the query without it to a seq scan.
In this case is more adviseable to define a second native query for the case without the country input and programaticaly check which query should be used