SQL improvements

Based on #386, #388 and #389.