added model and improved sql