Fix massive SQL query