tags:

views:

198

answers:

4

Ok here is my problem :

Before i start the description, let me to tell you that I have googled up a lot and I am posting this question for a good optimal solution :)

i am building a rest service on WCF to get userProfiles... the user can filter userProfiles by giving something like userProfiles?location=London

now i have the following method

GetUserProfiles(string firstname, string lastname, string age, string location)

the sql query string i built is: select firstname, lastname, .... from profiles where (firstName like '%{firstname}%') AND (lastName like '%{lastName}%') ....and so on with all variables being replaced by string formatter.

Problem with this is that it filters any row having firstname, lastname, age or location having a null value....

doing something like (firstName like '%{firstName}%' OR firstName IS NULL) would be tedious and the statement would become unmaintanable! (in this example there are only 4 arguments, but in my actual method there are 10)

What would be the best solution for this?....How is this situation usually handled?

Database used : MySql

+2  A: 
cletus
performance with so many unions??
glenn.danthi
@glenn: like I said, the four union variant is going to be mostly pointless **in this case** because the criteria won't use indexes anyway but if you were using indexes then that's a different story. The bigger issue is whether you're running the right query and whether your data model is suboptimal or not.
cletus
+1  A: 

You can use COALESCE(value,...)

coalesce(firstName, '') like '%{firstname}%'
astander
`COALESCE()` is basically an O(n) lookup as no indexes will be used.
cletus
A: 

You can use COALESCE:

select firstname, lastname, ....
from profiles
where (coalesce(firstName, '') like '%{firstname}%')
AND (coalesce(lastName, '') like '%{lastName}%')
Mark Byers
`COALESCE()` is basically an O(n) lookup as no indexes will be used.
cletus
Yes, obviously, but you can't use indexes anyway because of the `LIKE '%foo%'` so it seems to be a moot point here. The index can be used with `LIKE 'foo%' but not if there's a wildcard at the start. If performance is an issue here, a full text index should be used.
Mark Byers
A: 

You could always disallow null values in the first place - after all, everybody must be alive for some positive number of years and be somewhere geographically.

If you absolutely must allow nulls, then either use COALESCE, as others have suggested, or possibly IFNULL which is MySQL specific and may be slightly more optimal since it takes exactly 2 paramters.

Duncan