Fixed a few sql bugs