Fix query and add tests