Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Optimizing a certain query

I have a query that goes such:

bankNumber and BIC are both indexed.

SELECT * FROM `bank1` WHERE `bankNumber` <= 200000 or `BIC` = 'Berlin'

By using the EXPLAIN, it uses both of the keys in possible_keys. I read in an article that one of the things that not to do when queries for indicies is to use OR.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am tasked to optimize this query so that only one key gets used in the execution strategy.
What should I do in this case?

Things that I’ve tried:

Obviously went for AND, that did give me the desired result from EXPLAIN, but the data results are completely different.

>Solution :

AND obviously will produce different results. The only way to use indexes would be to union:

select bank1.* from (
    select id from bank1 where bankNumber <= 200000
    union distinct
    select id from bank1 where BIC='Berlin'
) ids
join bank1 on bank1.id=ids.id

But I question your entire goal; is the query in fact too slow? It doesn’t seem like you would have enough bank rows that a full table scan would be that bad.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading