Finished conversion into SQL query