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?