Skip to content
Advertisement

what are the alternative approaches to optimize this sql query?

I am just a beginner in sql and i am trying to optimize sql query but couldn’t get any idea yet, so i am sharing the query with you guys if anybody help me out through this will be very appreciated.

Tables are already indexed but if you have any composite indexing approach or anything you can share it.
Here is the code :

For particular case the sql query is :

There might be more values in IN clause but in this case there is only one for each IN clause.

some of the observation and their results :

  1. it takes more than 1.5s.
  2. Output of explain statement

Any kind of suggestion will be very helpful, Thanks so much in advance.

EDIT : The purpose of this sql is to pagination of deals stage wise, For example if the rank >= 0 and rank <= 20 then each of the stage has maximum 20 deals and rest of deals will be fetched in the next page.
Here is the image : Rank wise pagination
if the deal stage change the rank start with 1 and if it is from the same stage then rank will increment.

Advertisement

Answer

Your Javascript generates a so-called frankenquery — a query with many possible permutations of filter (WHERE) clauses. Each variant of your query will have its own ideal compound index.

Your EXPLAIN shows you already have an index on business_owner_id. And I guess your Javascript always generates a query saying WHERE business_owner_id = someConstant. So that’s a good starting point for optimization. If things still aren’t fast enough you may want to figure out which variants of your frankenquery are either slowest or most common or both.

For the variant you showed us, this compound index or some version of it might help.

Notice that lots of single-column indexes are generally harmful to database performance. Other than the indexes for primary keys and uniqueness constraints, your choice of indexes should be based on common query patterns.

By the way, I hope your deal_id column is the table’s primary key or has a unique index on it. If not, you’re misusing MySQL’s notorious nonstandard extension to GROUP BY, and the column values produced by your queries are unpredictable. Unpredictable results are no way to handle other peoples’ money.

A good reference is Marcus Winand’s https://use-the-index-luke.com/ online book.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement