more SQL optimisations (some fixes). Originally authored by @toporchillo. (!!!!!) REQUIRES pull request #544

Signed-off-by: Vadim A. Misbakh-Soloviov <mva@mva.name>