Rewrite SQL queries so the COALESCE part works correctly

* Resolves #985
* Resolves #1029