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 Queries and Execute them 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.
I think one more possible solution like:
String sql = "Select * from User where 1=1 "
if(phone!=null){
sql += " and phone = " + phone ;}
if(email!=null){
sql += " and email = " + email ;}
if(zip!=null){
sql += " and zip = " + zip ;}
OR You can try following single query:
select * from User
where (@phone is null OR phone = @phone) AND (@email is null OR email = @email) AND (@zip is null OR zip = @zip)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With