improved sql query building