fixed syntax errors, improved sql