Posted about 3 years ago. Visible to the public. Repeats. Linked content.

How to explain SQL statements via ActiveRecord

ActiveRecord offers an explain method similar to using EXPLAIN SQL statements on the database.

However, this approach will explain all queries for the given scope which may include joins or includes.

Output will resemble your database's EXPLAIN style. For example, it looks like this on MySQL:

Copy
User.where(id: 1).includes(:articles).explain
Copy
EXPLAIN for: SELECT `users`.* FROM `users`  WHERE `users`.`id` = 1 +----+-------------+-------+-------+---------------+ | id | select_type | table | type  | possible_keys | +----+-------------+-------+-------+---------------+ |  1 | SIMPLE      | users | const | PRIMARY       | +----+-------------+-------+-------+---------------+ +---------+---------+-------+------+-------+ | key     | key_len | ref   | rows | Extra | +---------+---------+-------+------+-------+ | PRIMARY | 4       | const |    1 |       | +---------+---------+-------+------+-------+   1 row in set (0.00 sec)   EXPLAIN for: SELECT `articles`.* FROM `articles`  WHERE `articles`.`user_id` IN (1) +----+-------------+----------+------+---------------+ | id | select_type | table    | type | possible_keys | +----+-------------+----------+------+---------------+ |  1 | SIMPLE      | articles | ALL  | NULL          | +----+-------------+----------+------+---------------+ +------+---------+------+------+-------------+ | key  | key_len | ref  | rows | Extra       | +------+---------+------+------+-------------+ | NULL | NULL    | NULL |    1 | Using where | +------+---------+------+------+-------------+   1 row in set (0.00 sec)

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Avatar
Arne Hartherz
Last edit:
about 3 years ago
by Besprechungs-PC
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more