Sample Header Ad - 728x90

effectiveness of creating index for ORDER BY column when used with many WHERE clauses

1 vote
1 answer
824 views
Say I am trying to build a pagination for a simple e-commerce app where user can search, filter, and sort items, and the result is displayed in an infinite scroll UI. I'm planning to use the cursor pagination method. When user wants to sort by lowest price (non-unique column), this means the cursor will comprise of ID and the price. Something like:
SELECT * FROM items
WHERE price > {last_price} OR (price = {last_price} AND id > {id})
ORDER BY price ASC, id ASC LIMIT 25
To optimize this query, I can create a compound index (price, id). https://dev.mysql.com/doc/refman/5.7/en/order-by-optimization.html Now my question is, will this index still be effective if the query contains many WHERE clauses? Because user can filter based on the item's attributes, e.g.
...
WHERE (locationId = 30 AND categoryId = 20 AND price > 5000 ...)     // filtering
AND (price > {last_price} OR (price = {last_price} AND id > {id}))   // cursor pagination clause
...
Based on my understanding, if we don't have the index, then the WHERE clause filtering will be done first to reduce the number of rows, and then ORDER BY is done on the remaining rows. But how's the case when there's an index present for the ORDER BY columns? Will it be useful at all or causing performance issue instead?
Asked by hskris (111 rep)
Dec 21, 2022, 06:04 AM
Last activity: Jan 7, 2025, 06:03 PM