Speed up SQL a bit & bug fix