Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute query when there are no values in where in clause

Tags:

java

mysql

I have a query that fetches results based on different id's, My query looks like this: I have shortened the query, still, there are two more WHERE In conditions.

 SELECT DISTINCT restaurant.*,branch.* 
 from restaurant,branch,restaurant_cuisines,restaurant_collections 
 WHERE restaurant.restaurant_id=branch.restaurant_id 
   AND restaurant_cuisines.cuisine_id IN (2,3) 
   AND restaurant_collections.collection_id IN ();

How to execute this query when there are no values in second WHERE in Condition? or How to handle this in application level(Java), I need to write around 28 if else conditions to check empty conditions. How to overcome this?

like image 437
Manju Avatar asked Apr 29 '18 09:04

Manju


People also ask

Can we use NULL in in clause?

It represents the absence of value so, it cannot be used for comparison. If you use it for comparison, it will always return NULL. In order to use NULL value in NOT IN Clause, we can make a separate subquery to include NULL values. We have the following demo_table in our geek's database.

IS NULL in SQL in WHERE clause?

SQL IS NULLWHERE IS NULL tests if a column has a NULL value. NULL is a special value that signifies unknown or no value. Testing for NULL with the = operator is not possible.

Do you need a WHERE clause for a query?

The SQL WHERE clause is something you must master if you wish to use SQL for working with data. It is arguably one of the most basic and must-learn constructs of SQL. In fact, in my experience, I have hardly found any data retrieval or manipulation queries that do not use a WHERE clause.


1 Answers

It all depends on your needs. Normally you should simply skip entire part.

As you use AND for all conditions I assume that by empty list you want to return all rows.(I guess that end users have some sort of multiple checkboxes or something like that).

If column is defined as NOT NULL you could generate your code in JAVA like this:

...
AND restaurant_collections.collection_id IN(restaurant_collections.collection_id)
-- which is always true and good query optimizer should skip entire part

When you want specific values you use it as previous:

...
AND restaurant_collections.collection_id IN (1,2,3)
like image 159
Lukasz Szozda Avatar answered Sep 17 '22 12:09

Lukasz Szozda