7

I have a query like this:

$stmt = $db->prepare("SELECT location.id FROM location WHERE location.city = :city AND location.country = :country");
$stmt->execute(array(':city' => $cityVar, ':country' => $countryVar));
$locationID = $stmt->fetchColumn();

I have faced a problem, because in database empty city column is sometimes null, sometimes empty string (I know it's wrong, but there is no way to change that). When my $cityVar variable is empty, I need to get all entries with needed country, but now I get only those where city column is empty string (I don't get those where city is null).

The only solution I come up with is to modify the query itself, for example:

$sql = "SELECT location.id FROM location WHERE location.country = :country ";
if ($cityVar) { 
   $sql .= "AND location.city = :city ";
}

but I was wondering if there is more legit ways to solve this problem. NOTE: there are more columns like city I need to search by.

1 Answer 1

14

Use COALESCE(city, '') - it will coerce NULL string to empty string "". If you have lots of cities and lots of queries to them, you can create an index on coalesced field to foster search.

"SELECT location.id FROM location WHERE COALESCE(location.city, '') = :city "
Sign up to request clarification or add additional context in comments.

4 Comments

Should I use it as WHERE COALESCE(location.city, "") = :city in my query?
Better solution is to update the table set null fields to empty strings ''. Is it possible?
Thank you. I know it would be a better way, but unfortunately it is impossible in this case.
but by using a function (coalesce here) on the column, your query clause won't be able to use the index on location.city if it exists ..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.