Fixed a few sql bugs

Some remarks though, will be placed in comments