Refactor queries

A number of low-level refactorings.
Some not very useful I guess (as per the idea to focus on commonalities).