Technology Programming

Speed Up Slow Queries Using EXPLAIN

An important trick for you to inspect slow SQL queries in Ruby on Rails could be the Postgres EXPLAIN command. Perhaps you might have seen that command in your web app logs. ActiveRecord throughout Ruby on Rails will always automatically re-run some sort of slow issue with EXPLAIN within the development environment. Using that command, you'll be able to gain observations into precisely what Postgres is doing to build results.

This post will have a look at one of several nice strategies to work with EXPLAIN to locate missing indexes. Suppose a line shows up similar to the following:

-> Seq Scan in automobiles (cost=... 123 rows=45 width=678)

This means the Postgres server identified it needs to iterate one-by-one through result sets. If the thing is that a 'Seq Scan' inside your app logs, it is usually an excellent indicator of a lacking SQL index.

Take a review of your query that is running through EXPLAIN. Postgres informs us this 'Seq Scan' will go through your automobiles results record. When you continue to dig through your app logs, you can also see some sort of Filter series. This is a superb place to get a part of one's query which indicates precisely what column exists in some sort of WHERE clause, and so needs an index.

The solution is to produce a Rails migration to create the index using the create_index line.

Soon after creating that migration, I'm able to say this kind of query has substantially sped up. In addition to that, I no longer see this EXPLAIN inside my app logs.

Note that whenever your site is running in production, ActiveRecord is not going to attempt to re-run slower queries utilizing EXPLAIN because of performance issues. Running EXPLAIN requires re-running some sort of slow query a second time (after it is deemed slow), so as to output the total query approach as generated from the database.

Always thoroughly run your app in development mode prior to attempting to show it in production so as to benefit from ActiveRecord's slow query features. Moreover, if you're using a tool such as New Relic, you may get alerts about slow inquiries, which you can subsequently try running again while in development mode.

There are usually many additional approaches to speed up your slower SQL queries, and EXPLAIN is just one choice. But it has been a quick strategy to use to fix functionality problems. To learn more, I highly recommend reading further concerning the Postgres EXPLAIN command for you to optimize slower queries throughout Rails in the ElegantRuby.com site.

Hope this really is helpful to you too!

Leave a reply