Reputation: 2121
In Rails there is a useful method that can show how long a query takes and what query it is.
The method is 'explain'
So I can do:
User.where(name: 'Johnny').explain
And it will display the actual sql query.
the 'count' method also makes an sql query but since 'count' returns a number and not an active record, I cannot use explain on it. Is there any way to do that?
Upvotes: 1
Views: 295
Reputation: 8345
This works:
User.select('count(*)').where(name: 'Johnny').explain
EDIT: This is indeed exactly the same:
irb(main):004:0> Benutzer.where(login: 'xxx').count
(2.2ms) SELECT COUNT(*) FROM "BENUTZER" WHERE "BENUTZER"."LOGIN" = 'xxx'
=> 0
irb(main):005:0> Benutzer.select("count(*)").where(login: 'xxx').explain
Benutzer Load (0.9ms) SELECT count(*) FROM "BENUTZER" WHERE "BENUTZER"."LOGIN" = 'xxx'
=> EXPLAIN for: SELECT count(*) FROM "BENUTZER" WHERE "BENUTZER"."LOGIN" = 'xxx'
Plan hash value: 1339361075
-------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
-------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 1 | 12 | 2 (0)| 00:00:01 |
| 1 | SORT AGGREGATE | | 1 | 12 | | |
|* 2 | TABLE ACCESS FULL| BENUTZER | 1 | 12 | 2 (0)| 00:00:01 |
-------------------------------------------------------------------------------
Predicate Information (identified by operation id):
---------------------------------------------------
2 - filter("BENUTZER"."LOGIN"='xxx')
Note
-----
- dynamic sampling used for this statement (level=2)
Upvotes: 2