Query Builder limit and offset behavior with high-volume datasets
0 reputation · 01 Sept 2020, 02:42 UTC
0 reputation · 01 Sept 2020, 02:42 UTC
CodeIgniter's Database Query Builder provides limit() and offset() methods to abstract result constraints across different database drivers. This functionality is frequently used in conjunction with the Pagination class to manage large record sets by calculating the starting index and page size.
While these methods ensure cross-database compatibility, the underlying SQL execution for offset-based pagination typically requires the database to scan and discard rows prior to the specified offset. In environments with high-volume tables, this can lead to performance degradation as the offset value increases.
What are the architectural limits of the Query Builder's offset implementation regarding execution time on large datasets? Are there documented alternatives within the framework to implement keyset pagination to avoid the performance overhead of offset()?
The Query Builder’s limit() and offset() methods simply add LIMIT ? OFFSET ? to the generated SQL. The database must read and discard all rows up to the offset before returning the limited set, so execution time grows roughly linearly with the offset value.
$this->db->last_query(); after building the query with limit/offset.EXPLAIN (or EXPLAIN ANALYZE) to see the cost of scanning/skipping rows.$this->db->where('id >', $lastId)->orderBy('id')->limit($pageSize); (adjust column and operator as needed).To give a precise recommendation, please confirm which database driver you are using (e.g., MySQL, PostgreSQL, SQL Server).
Use comments to ask for clarification. Post a solution as an answer.
34,275 reputation · 01 Sept 2020, 11:23 UTC
When the database can satisfy the ORDER BY and selected columns from an index (a covering index), it may perform an index‑only scan. The engine still has to walk through the index entries up to the offset, so the CPU cost grows linearly with the offset, but the amount of data read from disk can be much lower. This behavior is observable with EXPLAIN showing “Using index” and rows examined equal to offset + limit. In CodeIgniter v4 the builder simply passes the offset value to the driver; there is no special handling to turn OFFSET into a keyset lookup.