From 3cb656fe99ad5e5a0f2130013b28c7e7c1a4feac Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Sun, 1 May 2016 17:15:44 -0500 Subject: [PATCH] Add Perform SQL Explain With ActiveRecord as a rails til --- README.md | 3 ++- .../perform-sql-explain-with-activerecord.md | 24 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 rails/perform-sql-explain-with-activerecord.md diff --git a/README.md b/README.md index 9341352..87f68ba 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ variety of languages and technologies. These are things that don't really warrant a full blog post. These are mostly things I learn by pairing with smart people at [Hashrocket](http://hashrocket.com/). -_407 TILs and counting..._ +_408 TILs and counting..._ --- @@ -268,6 +268,7 @@ _407 TILs and counting..._ - [Ignore Poltergeist JavaScript Errors](rails/ignore-poltergeist-javascript-errors.md) - [Migrating Up Down Up](rails/migrating-up-down-up.md) - [Params Includes Submission Button Info](rails/params-includes-submission-button-info.md) +- [Perform SQL Explain With ActiveRecord](rails/perform-sql-explain-with-activerecord.md) - [Pretend Generations](rails/pretend-generations.md) - [Rescue From](rails/rescue-from.md) - [Retrieve An Object If It Exists](rails/retrieve-an-object-if-it-exists.md) diff --git a/rails/perform-sql-explain-with-activerecord.md b/rails/perform-sql-explain-with-activerecord.md new file mode 100644 index 0000000..c1532fe --- /dev/null +++ b/rails/perform-sql-explain-with-activerecord.md @@ -0,0 +1,24 @@ +# Perform SQL Explain With ActiveRecord + +Want to check out the performance characteristics of some SQL query from +within a Pry session? `ActiveRecord` allows you to perform a SQL `explain` +on any `ActiveRecord::Relation` object. After chaining some Arel functions +together, add an `#explain`. + +Here is an example: + +```ruby +Recipe.all.joins(:ingredient_amounts).explain + Recipe Load (0.9ms) SELECT "recipes".* FROM "recipes" INNER JOIN "ingredient_amounts" ON "ingredient_amounts"."recipe_id" = "recipes"."id" +=> EXPLAIN for: SELECT "recipes".* FROM "recipes" INNER JOIN "ingredient_amounts" ON "ingredient_amounts"."recipe_id" = "recipes"."id" + QUERY PLAN +---------------------------------------------------------------------------- + Hash Join (cost=1.09..26.43 rows=22 width=148) + Hash Cond: (ingredient_amounts.recipe_id = recipes.id) + -> Seq Scan on ingredient_amounts (cost=0.00..21.00 rows=1100 width=4) + -> Hash (cost=1.04..1.04 rows=4 width=148) + -> Seq Scan on recipes (cost=0.00..1.04 rows=4 width=148) +(5 rows) +``` + +[source](https://robots.thoughtbot.com/why-postgres-wont-always-use-an-index)