Fixes to SQL optimisation by @toporchillo

(!!!!!) REQUIRES PR #544