sql now fixed to be more efficient (only doing joins if criteria
selected)