fixing some bugs in sql