How to write a collection SQL query