<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Lucas Grossi on Medium]]></title>
        <description><![CDATA[Stories by Lucas Grossi on Medium]]></description>
        <link>https://medium.com/@lucas.grossi?source=rss-fa713dd7726c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*xA3YKvuy10JHVzg1</url>
            <title>Stories by Lucas Grossi on Medium</title>
            <link>https://medium.com/@lucas.grossi?source=rss-fa713dd7726c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 21:03:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lucas.grossi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Indexing multiple range conditions in MySQL: a case study]]></title>
            <link>https://medium.com/mollie-payments/indexing-multiple-range-conditions-in-mysql-a-case-study-bf782a41c18?source=rss-fa713dd7726c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf782a41c18</guid>
            <category><![CDATA[indexing]]></category>
            <category><![CDATA[index]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[optimization]]></category>
            <dc:creator><![CDATA[Lucas Grossi]]></dc:creator>
            <pubDate>Tue, 08 Dec 2020 16:18:48 GMT</pubDate>
            <atom:updated>2020-12-08T16:18:48.066Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iiH3RPQ52jJ3LQm6olPj0A.jpeg" /><figcaption>Illustration by <a href="https://www.svenfranzen.com/">Sven Franzen</a></figcaption></figure><p>While working on improving the performance of one of the slowest MySQL queries our team’s system was generating, we faced an interesting scenario that led to valuable discussions and insights. In this article, I’ll go through this scenario, highlighting some details that must be considered when building indices for complex queries.</p><blockquote>This article is an overview of a complex indexing use case we faced. To keep it short, I will explain only the main indexing concepts directly related to the example. Some basic MySQL indexing background might be required to follow along.</blockquote><h3><strong>Scenario</strong></h3><p>The examples in this article are based on the following table.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/117ee3346ea8d2cfd9b45296b8ecb6ea/href">https://medium.com/media/117ee3346ea8d2cfd9b45296b8ecb6ea/href</a></iframe><p>Let’s consider that <em>blog_index_example_table</em> is a large table, with millions of rows. We are aiming to efficiently query this table using:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df1c86a56242607100d09621e287c103/href">https://medium.com/media/df1c86a56242607100d09621e287c103/href</a></iframe><p><strong>With millions of rows, this query would definitely require an index to perform well. How do we structure that index, though?</strong> The first instinct for many of us, including myself, is probably to add a <strong>four-</strong>columns compound index like <em>ready_to_be_processed_idx_2</em>.</p><p>This index fits the proposed query, and indeed allows it to run in a few milliseconds. However, this index actually uses more resources than we need. Let me explain.</p><h3>MySQL is smart — you can make it smarter, though</h3><p>As many of you already know, the conditions order in the WHERE clause doesn’t matter at all. MySQL is smart enough to find the best index to use and reorder the conditions accordingly.</p><p>However, MySQL doesn’t reorder your <strong>index</strong> to perform it more efficiently depending on your clauses. It would cost a lot of resources, and it still would not always be able to predict the scenarios correctly. In other words: <strong>the column order in the index matters</strong> (a lot).</p><p>The optimal order of the columns in your index isn’t always the same though. It depends on your data and needs. In the case above, the <em>processed_at</em><strong><em> </em></strong>condition filters out the highest amount of rows. For this reason, we chose it as the first column of our index. Unfortunately, the other three are quite similar in filtering range. So, how to choose the proper index order for them?</p><h3>Conditions</h3><p>There are still three conditions without index left in our query. We need to add those columns to our index, however we are not 100% sure which order we should follow. A good start is to look into the type of the conditions. Are they single conditions or range conditions? I’ll explain the difference.</p><h4>Single Conditions</h4><p>Let’s first look at the <em>canceled_at</em> condition:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4955f164d3da49c74353ab814e694511/href">https://medium.com/media/4955f164d3da49c74353ab814e694511/href</a></iframe><p><em>IS NULL</em> might look like it’s a non-singular value at first glance, since <em>NULL</em> stands for an undefined value. However, if we look more closely, <em>NULL</em> is a single and concrete value, thus countable and indexable. In other words, we can list <em>NULL</em> as a specific value: 10, 20, 500, 15, 0, <em>NULL</em>, 1, 10923… Based on that, we can conclude that the piece of query above is a <strong>single condition,</strong> since it points to a well-defined value.</p><h4>Range Conditions</h4><p>Now, let’s take a look at the remaining ones:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66729f1d12a6d336bdc8f6f66aea875f/href">https://medium.com/media/66729f1d12a6d336bdc8f6f66aea875f/href</a></iframe><p>Do you notice the difference? <em>booking_confirmed_at </em>and <em>to_be_processed_at </em>do not stand for a unique value, but a range of values. After this, everything that gets indexed will lose effectiveness, since MySQL now needs to look inside this subset of values to proceed with any index search.</p><p><strong>Golden rule: always first index the columns where the related conditions are single value only, then focus on range conditions.</strong></p><p>As such, we’ve chosen <em>canceled_at</em> as our second index column. What now?</p><h4><strong>Multiple Range Conditions</strong></h4><p>Now, there are two remaining conditions we want to add to our index. Both are range conditions with a similar filtering range. Which ones should we use, and in which order? Instinctively, you might feel you can add both in any order. Giving priority to the condition that filters out a little bit more or that makes the same compound index reusable might prove useful in other scenarios. That is a fair assumption, but it’s only <strong>half correct</strong>.</p><p>At this point, most of the decisions we made here will lead to similar results. It is highly advised to choose the third column of this index based on the condition that filters out more rows. Also, if applicable, it is good to build the compound index in a way that allows it to be used in other scenarios. <strong>Reducing the amount of indices, and their size, is a good space and performance optimisation</strong>.</p><p>In this case, <strong>we have multiple range conditions</strong>. As we explained, a range condition will have its own range of things to go over before using the index. That’s the main concept needed to understand our use case:</p><blockquote>Once you reach the first range condition, any subsequent condition in your query will not use any further indices</blockquote><p>As such, adding both will not change query performance. It will just take more disk space to store the index. You will have exactly the same query speed with or without the fourth column, which I will demonstrate with an example below. The best choice in our case would be an index with three columns, choosing the most suitable to your scenario between the remaining two columns.</p><p>We decided to move on with <em>processed_at, canceled_at, to_be_processed_at</em>. It fits our scenarios better, based on the row ranges and potential usage of this index in other queries.</p><h3><strong>The book catalog example</strong></h3><p>Imagine an animal catalog indexed by ‘name’ and ‘color’. Its index is organized somewhat like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ceb0b7f1d3e7faeb839524c3e7e0682b/href">https://medium.com/media/ceb0b7f1d3e7faeb839524c3e7e0682b/href</a></iframe><p>Now, let’s perform some querying over this catalog and see how it would use this page index:</p><ol><li><strong>Punctual conditions</strong></li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b82fd52338f91f3f8847b0dd3da03b75/href">https://medium.com/media/b82fd52338f91f3f8847b0dd3da03b75/href</a></iframe><p>Notice that with a simple index search you can find exact page values for those queries. There is always one value to the condition pair. No need to go through the pages or do any further search.</p><p>2. <strong>Range condition after punctual condition</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa3b82c13a61206143eff8f2a2852f0a/href">https://medium.com/media/fa3b82c13a61206143eff8f2a2852f0a/href</a></iframe><p>Note that there is, now, an extra step to find the pages for our values. It’s still very straightforward, although a bit more complex than ‘case 1’. The first part of the index narrows down your options to one type. Then, you just need to exclude the color you don’t want and you’ll have the range of pages where your results are. You needed to check a few extra indices, but that is not a big deal. MySQL would do that quite efficiently.</p><p>3. <strong>Range conditions first</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15258dee13f2dc1f7eaf868070b8762c/href">https://medium.com/media/15258dee13f2dc1f7eaf868070b8762c/href</a></iframe><p>Now it got complicated. Your range of indices is much higher than previously and you can’t use the indices properly. An almost full index scan is needed to identify the key pairs that match your query. This is where MySQL also struggles. The more values you have, the bigger your indices become, thus more data to scan. It ends up not much different from a table scan, i.e. going through the full table row-by-row. Efficiency was compromised.</p><p>Looking at our initial query, this example clarifies why adding <em>booking_confirmed_at</em> would not change the index behaviour nor speed up the query.</p><p>We will now prove the above using MySQL <em>explain</em>.</p><h3>Proof</h3><p>We will use <em>explain</em> to analyse how two different indices perform over the query we’ve been discussing in this article. Both indices have the same columns and order, but one of them has an extra fourth column. From the create table statement, we have:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed4ca10e166c25b89ee3ba6dc0bffbcc/href">https://medium.com/media/ed4ca10e166c25b89ee3ba6dc0bffbcc/href</a></iframe><p>Running the query in the top of this article, we have the following results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x4iwvambIKcpoNiM" /><figcaption>Explain run using `ready_to_be_processed_idx_1` containing three columns</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c-6XkhiPlP5TagYK" /><figcaption>Explain run using `ready_to_be_processed_idx_2` containing four columns</figcaption></figure><p>We can see that both used the same key range (17). That means that they used the same part of the index and that the extra fourth column was ignored.</p><p>You can do a small tweak to your query that allows it to use the four-columns index fully. We will change the condition of <em>to_be_processed_at</em> to a single condition: <em>to_be_processed_at = &quot;2020-10-08 09:45:02&quot;</em>. That way, we now have only <strong>one</strong> range condition. See the results below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JkimfCA6x68exN3D" /><figcaption>Explain run using `ready_to_be_processed_idx_2` showing a scenario where all the four columns are used</figcaption></figure><p>You should have noticed that we now use a key_range of 23, meaning that it now uses a higher range of our index, as expected. Though this proves we can use the fourth index, it’s not suitable for our real case, since we need the date range query.</p><h3>Final thoughts</h3><p>All the three possibilities listed in this article work for our case — both three column indices and the four column index. However, using the four-column index requires <strong>more resources</strong>: more indices lead to bigger tables and slower updates, but deliver the same query response times. Choosing a three-column index optimizes our query the most: for both performance and disk space. In the end, we moved from a 6s execution time to 17ms for the same query.</p><p>Indices might look simple at first, and their idea is quite straightforward. However, spending some time on optimizing your index usage can bring about dramatic improvements in performance and disk footprint.</p><p>This showcase aimed to demonstrate some of the considerations that are important to keep in mind while creating or optimizing SQL indices.</p><blockquote>Are you looking for a nice place to work? We are hiring engineers! Check out our vacancies on <a href="https://jobs.mollie.com/?tags%5B%5D=department%2CProduct%20Engineering&amp;">https://jobs.mollie.com/</a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf782a41c18" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mollie-payments/indexing-multiple-range-conditions-in-mysql-a-case-study-bf782a41c18">Indexing multiple range conditions in MySQL: a case study</a> was originally published in <a href="https://medium.com/mollie-payments">Mollie</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>