Change the way the sorting of the result of the query is done.

Only sort as long as we need to, stop when we reach desired number of rows.