DEV Community

Discussion on: 1 SQL Query You Should Stop Using

Collapse
 
alaindet profile image
Alain D'Ettorre

It's always about memory vs CPU: using the ID is much faster because the ID field is usually the primary key hence it's indexed, meaning each value is literally assigned a number internally because numbers are great for sorting. For example, when the machine sees "WHERE id > 123 LIMIT 10" it can throw out any smaller id right away and just get those 10 rows, while "OFFSET 123 LIMIT 10" means you perform a query getting 133 rows and then discard 123 rows.

In order to get rid of OFFSET in pagination queries and still have filters in the WHERE clause and custom sorting, you just need to index any table field you want rows to be sorted by, so that each row of that field internally has a number to refer to.

Collapse
 
abdisalan_js profile image
Abdisalan

That’s a good clarification, the cursor pagination methods rely on there being an index to reduce the lookup time for the where clause.

Without an index the query goes much slower.