a few sql optimisations