Tests and improved sql