SQL optimisations. Originally authored by @toporchillo.

Signed-off-by: Vadim A. Misbakh-Soloviov <mva@mva.name>
Merge pull request #549 from ocStore/master

catalog SQL optimisations.