Sql: construct queries properly when condition involves nulls

Subject. :octocat: