Selecting rows from table by custom query