Numerous sql fixes