Fix sql statement so only one call to db