Sql: construct queries properly when condition involves nulls