What is query optimization with explain in Rails?

Answer

ActiveRecord's explain method runs EXPLAIN (or EXPLAIN ANALYZE in PostgreSQL) on the generated SQL and returns the query execution plan. Usage: User.where(active: true).explain. The output shows whether the database uses an index scan or a full sequential scan. Look for: Seq Scan (bad for large tables — add an index), Index Scan or Index Only Scan (good), and actual vs. estimated row counts. For complex queries, EXPLAIN ANALYZE shows actual execution time per node. Combine with the PgHero gem or rack-mini-profiler to identify slow queries in development and production.