Added tests and refactorized query