Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSql remove difference between null and empty string

Tags:

sql

postgresql

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.

like image 403
Mindaugas Jakubauskas Avatar asked Jul 20 '26 02:07

Mindaugas Jakubauskas


1 Answers

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 "
like image 200
Eugene Lisitsky Avatar answered Jul 21 '26 16:07

Eugene Lisitsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!