Remove double WHERE in SQL

Closes #988