<?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 Mehnaz Bano on Medium]]></title>
        <description><![CDATA[Stories by Mehnaz Bano on Medium]]></description>
        <link>https://medium.com/@mehnazbano?source=rss-5fe769f46834------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Ci9QbXMVzkXGokjL.</url>
            <title>Stories by Mehnaz Bano on Medium</title>
            <link>https://medium.com/@mehnazbano?source=rss-5fe769f46834------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 21:36:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mehnazbano/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[How to analyse database queries in rails?]]></title>
            <link>https://medium.com/@mehnazbano/explaining-database-queries-in-rails-614354724ce?source=rss-5fe769f46834------2</link>
            <guid isPermaLink="false">https://medium.com/p/614354724ce</guid>
            <category><![CDATA[sql-query-performance]]></category>
            <category><![CDATA[performance-analysis]]></category>
            <category><![CDATA[psql]]></category>
            <category><![CDATA[database-performance]]></category>
            <category><![CDATA[query-optimization]]></category>
            <dc:creator><![CDATA[Mehnaz Bano]]></dc:creator>
            <pubDate>Sat, 11 Mar 2023 14:23:11 GMT</pubDate>
            <atom:updated>2023-03-11T20:36:56.470Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, we will learn how to use <strong>Explain</strong> and <strong>Analyze</strong> on active record relation or sql queries. In order to track down our query performance.</p><p>We often do query performance analysis in order to decide the ideal way to fetch records from the database. This is very important step in order to improve the performance of your application.</p><p>To ananlysis and compare performance, I’ve created a <strong>users</strong> table and seeded with <strong>100000</strong> dummy records. Below is my users migration code.</p><pre>class CreateUsers &lt; ActiveRecord::Migration[7.0]<br>  def change<br>    create_table :users do |t|<br>      t.string :first_name<br>      t.string :last_name<br>      t.string :email, null: false<br>      t.string :phone<br>      t.timestamps<br>    end<br>  end<br>end</pre><p>To seed data into users table:</p><pre>100000.times { |i| User.create(first_name: &#39;Test&#39;, last_name: &#39;User&#39;, email: &quot;test_user+#{i}@gmail.com&quot;) }</pre><ol><li><strong>Using ActiveRecord <em>Explain</em></strong></li></ol><p>Explain will provide the query plan i.e how it plans to execute the query. It will convert active record query into sql and run explain command on top of it.</p><pre>&gt; User.where(email: &#39;test_user@gmail.com&#39;).explain<br>  User Load (25.5ms)  SELECT &quot;users&quot;.* FROM &quot;users&quot; WHERE &quot;users&quot;.&quot;email&quot; = $1  [[&quot;email&quot;, &quot;test_user@gmail.com&quot;]]<br>=&gt;                                         <br>EXPLAIN for: SELECT &quot;users&quot;.* FROM &quot;users&quot; WHERE &quot;users&quot;.&quot;email&quot; = $1 [[&quot;email&quot;, &quot;test_user@gmail.com&quot;]]<br>                       QUERY PLAN          <br>---------------------------------------------------------<br> Seq Scan on users  (cost=0.00..3523.00 rows=1 width=91)<br>   Filter: ((email)::text = &#39;test_user@gmail.com&#39;::text)<br>(2 rows)</pre><p>As you can see in the response, query plan is to run <em>seq scan(sequential scan) </em>which means it will check for each and every record and filter out the record if email matches our condition, which does not seem very efficient.</p><p>The second thing the planner is telling us, is a <strong>cost estimation</strong> <em>cost=0.00..3523.00</em>. For that it gives us two values. The first one, 0.00, is the <strong>start-up cost</strong>, which is the estimated cost to initialize everything before the output phase starts. The second one, <em>3523.00</em>, is the <strong>total cost</strong>, which is an estimation on how much cost it will take to fully execute the query.</p><p><strong>Rows</strong> is the estimated number of rows the output will contain.</p><p>While <strong>width</strong> is the average width in bytes for those rows.</p><p><strong>Adding index to our users table</strong></p><p>To compare and analyse the query performance after adding index. I’ve added index on users <em>email</em>(B-tree index for exact match)<em>.</em></p><pre>class AddIndexToUsers &lt; ActiveRecord::Migration[7.0]<br>  def change<br>    add_index :users, :email<br>  end<br>end<br></pre><p>Running the same query again after adding index, gives below result</p><pre>&gt; User.where(email: &#39;test_user@gmail.com&#39;).explain<br>  User Load (1.8ms)  SELECT &quot;users&quot;.* FROM &quot;users&quot; WHERE &quot;users&quot;.&quot;email&quot; = $1  [[&quot;email&quot;, &quot;test_user@gmail.com&quot;]]<br>=&gt; <br>EXPLAIN for: SELECT &quot;users&quot;.* FROM &quot;users&quot; WHERE &quot;users&quot;.&quot;email&quot; = $1 [[&quot;email&quot;, &quot;test_user@gmail.com&quot;]]<br>                                    QUERY PLAN<br>-----------------------------------------------------------------------------------<br> Index Scan using index_users_on_email on users  (cost=0.42..8.44 rows=1 width=91)<br>   Index Cond: ((email)::text = &#39;test_user@gmail.com&#39;::text)<br>(2 rows)</pre><p>Now we see a completely different situation.</p><p>After adding indexes, as you can see neither the <strong>query</strong>, nor the values <strong>rows</strong> and <strong>width</strong> have changed. But <strong>we have a completely different query plan, and</strong> with it, <strong>a completely different cost estimation.</strong></p><p>The query plan is now performing an <strong>Index Scan</strong> checking the index condition, and we can also check that the new index that we just created (<em>index_users_on_email</em>) is being used and it improves overall query cost.</p><p>2.<strong> Executing SQL query</strong></p><p>By default, rails doesn’t provide interface to explain and analyze the query performance.</p><p>If you need to know more information like the query planning or execution time, you can use EXPLAIN ANALYZE command, it will actually run the query and provide more information on the overall performance of the query.</p><p><em>Use to_sql</em> method will help us to convert the active record query into sql statement, which can be executed using execute method.</p><pre>&gt; ActiveRecord::Base.connection.execute(<br>  &quot;EXPLAIN ANALYZE #{User.where(email: &#39;test_user@gmail.com&#39;).to_sql}&quot;<br>).values<br><br>EXPLAIN ANALYZE SELECT &quot;users&quot;.* FROM &quot;users&quot; WHERE &quot;users&quot;.&quot;email&quot; = &#39;test_user@gmail.com&#39;<br>=&gt; <br>[[&quot;Index Scan using index_users_on_email on users  (cost=0.42..8.44 rows=1 width=91) (actual time=0.028..0.029 rows=0 loops=1)&quot;],<br> [&quot;  Index Cond: ((email)::text = &#39;test_user@gmail.com&#39;::text)&quot;],<br> [&quot;Planning Time: 0.126 ms&quot;],<br> [&quot;Execution Time: 0.050 ms&quot;]]</pre><p>Planning time in EXPLAIN EXECUTE includes the time required to fetch the plan from the cache and the time required for re-planning, if necessary.</p><p>Execution time is the time was spent executing the query.</p><p>3.<strong> Using PostgreSQL CLI</strong></p><p>All of these prior examples have been run from within a Rails process such as the Rails console. However, we can skip Rails entirely and use our database directly. In our case with PostgreSQL, we can use psql.</p><pre>&gt; psql -U postgres<br>&gt; postgres=# \l<br>&gt; postgres=# \c test_db<br>&gt; test_db=# EXPLAIN select * from users where email = &#39;test_user@gmail.com&#39;;</pre><p>Again, we have all the features available to us that our database engine supports, so we can use EXPLAIN or EXPLAIN ANALYZE or any other functionality, without needing it to be built into Rails. This gives us all the power our database provides, but we lose the expressiveness of ActiveRecord&#39;s query API - or rather, we need to find the .to_sql representation of the query we&#39;re interested in prior to using this.</p><p>4.<strong> Using gem activerecord-analyze</strong></p><p>If you’re willing to take on a dependency to get some additional explanatory power, are using ActiveRecord 4 through 6, and use PostgresSQL, then you can reach for the <a href="https://github.com/6/activerecord-explain-analyze">activerecord-explain-analyze</a> gem.</p><p>Now you can specify the output formatting of your EXPLAIN results, and call<br>EXPLAIN ANALYZE:</p><pre>&gt; User.where(email: &quot;test@example.com&quot;).explain(analyze: true)<br><br>User Load (8.7ms)  SELECT &quot;users&quot;.* FROM &quot;users&quot; WHERE &quot;users&quot;.&quot;email&quot; = $1  [[&quot;email&quot;, &quot;test_user@gmail.com&quot;]]<br>=&gt;                    <br>EXPLAIN for: SELECT &quot;users&quot;.* FROM &quot;users&quot; WHERE &quot;users&quot;.&quot;email&quot; = $1<br>Index Scan using index_users_on_email on public.users  (cost=0.42..8.44 rows=1 width=91) (actual time=0.004..0.004 rows=0 loops=1)<br>  Output: id, first_name, last_name, email, phone, created_at, updated_at<br>  Index Cond: ((users.email)::text = &#39;test_user@gmail.com&#39;::text)<br>  Buffers: shared hit=3<br>Planning Time: 0.035 ms<br>Execution Time: 0.010 ms</pre><h3>Which to Use</h3><p>If you’re interested in quickly getting an execution plan of an existing ActiveRecord query, start with using ActiveRecord’s explain method.</p><p>Should you need more functionality that your database engine provides, you can execute any query you would like to your database through ActiveRecord.</p><p>If you need that additional functionality, such as EXPLAIN ANALYZE, on a regular basis, consider taking on an additional dependency that&#39;ll provide that for you, such as <a href="https://github.com/6/activerecord-explain-analyze">activerecord-explain-analyze</a> or <a href="https://github.com/bradurani/pg-eyeballs">pg-eyeballs</a> or <a href="https://github.com/pawurb/rails-pg-extras">Rails PG Extras</a> or <a href="https://github.com/ankane/pghero">PgHero</a>. With PgHero you can even go all pro and visualize a query plan using a <a href="https://tatiyants.com/pev/#/plans/new">visualizer tool</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=614354724ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>