Not an SQL expert:
I am currently implementing a Searching Web Application. The user will send a GET request to a particular Endpoint.
The Endpoint will accept a set of URL Params and the request can come with optional fields. Such as 1, 2 or 3 fields.
My Database table for USER looks like this.
+--------------+---------+------+-----+---------+----------------+
| id | firstName | lastName | email | zip | phone |
+--------------+---------+------+-----+---------+----------------+
Now the web application will get a GET Request with either Phone or Zip or Email.
I have two solutions for doing this but both look bad:
Solution 1:
Have multiple
SQL QueriesandExecutethem according to the URL Params, I receive.Select * from User where phone=1111111111 and zip=12345 and [email protected];Select * from User where phone=1111111111 and zip=12345;... ...
And so on........I will end up having many queries and this will be a bad implementation. Also will be bad to maintain.
Solution 2:
Other solution that I am thinking of is to have a method, which will build an SQL query based on the URL Params I receive.
Example:
buildSQLQuery(phone,zip,email){
String sql = "Select * from User where "
if(phone!=null && email!=null && zip!=null ){
sql = sql + "phone = " + phone + " and zip = " + zip + " and email = " + email;
}else if (phone!=null && email!=null && zip==null){
sql = sql + "phone = " + phone + " and email = " + email;
}
.......
......
And so on have all conditions and build that particular query.
}
I don't like both these solutions.
Is there a way to write a Single SQL query and that will handle all the above conditions.
Something like if the URL Param value is NULL then that should not affect the query and I will get my expected results.
As in my case the optional values, which don't come in are set to NULL.
Can I implement something like this?
Select * from User where (if notNull (phone))(phone = phone ) and (if notNull (email))(email = email ) and (if notNull (zip))(zip = zip )
If any of the above one value is null then don't use that part in where Condition.
Also I will always have one field present, so there will be no case where all values are null.
I am implementing this web application in Java and Spring MVC. If anyone can guide me in the correct direction.
Thank you.
if()if you providefiddlefor your table here it will be easy to find solution.