Fix sql query. closes #1968