mirror of
https://github.com/jbranchaud/til
synced 2026-01-03 15:18:01 +00:00
Add Perform SQL Explain With ActiveRecord as a rails til
This commit is contained in:
@@ -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)
|
||||
|
||||
24
rails/perform-sql-explain-with-activerecord.md
Normal file
24
rails/perform-sql-explain-with-activerecord.md
Normal file
@@ -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)
|
||||
Reference in New Issue
Block a user