Abstract SQL into select function

This is modifiable with a block, so we should be able to do any kinds of
queries we like without rewriting a lot of boilerplate.