Fix pagination SQL query