Improve handling of database queries with many rows