Fix SQL query

It's slow now, but it works.