Fix query generation bug