1

I have the following table structure.

id (INT) index
date (TIMESTAMP) index
companyId (INT) index

This is the problem I am facing

companyId 111: hasta a total of 100000 rows in a 1 year time period.

companyId 222: has a total of 8000 rows in a 1 year time period.

If companyId 111 has 100 rows between '2020-09-01 00:00:00' AND '2020-09-06 23:59:59' and companyId 222 has 2000 rows in the same date range, companyId 111 is much slower than 222 even if it has less rows in the selected date range.

Shouldn't MySQL ignore all the rows outside the date range so the query becomes faster?

This is a query example I am using:

SELECT columns FROM table WHERE date BETWEEN '2020-09-01 00:00:00' AND '2020-09-06 23:59:59' AND companyId = 111;

Thank you

3
  • Please post TEXT results of SHOW CREATE TABLE table; so we can see if you have applied any of the suggestions to this point in time. Someone will help you get high performance. Commented Sep 13, 2020 at 20:05
  • Would you have time to post current TEXT results of SHOW CREATE TABLE table; so we can see what you ended up with for a table with indexes? Commented Oct 12, 2020 at 20:17
  • It would be ok to respond - No. We would understand. Commented Nov 11, 2020 at 20:36

1 Answer 1

2

I would suggest a composite index here:

CREATE INDEX idx ON yourTable (companyId, date);

The problem with your premise is that, while you have an index on each column, you don't have any indices completely covering the WHERE clause of your example query. As a result, MySQL might even choose to not use any of your indices. You can also try reversing the order of the index above to compare performance:

CREATE INDEX idx ON yourTable (date, companyId);
Sign up to request clarification or add additional context in comments.

5 Comments

Should I create this new Index and leave the others intact or should I edit/remove them?
@CrashOverride - Please provide SHOW CREATE TABLE; we can't guess at what other indexes you have. In general, toss any index that is the left part of another index.
Put companyID first because it is tested with"=". Then all the necessary 'rows' of the index are consecutive.
@RickJames I also would have suggested the first version under the assumption that companyId would have higher cardinality.
Cardinality is not relevant. The structure of the index is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.