When debugging slow SQL queries, it’s helpful to understand the database engine's query plan. Whenever you execute a declarative SQL query, the database generates a "query plan" that outlines the exact steps the engine will take to execute the query. Most of the time, we don’t need to worry about this plan because SQL engines are highly optimized and can generate efficient execution strategies automatically. However, if a query is slow, inspecting the generated plan can help identify bottlenecks and optimization opportunities.
If you're using ActiveRecord, you can retrieve a query plan by executing
explain
Show archive.org snapshot
:
User.where(name: "demo").explain
To visualize a PostgreSQL query plan, you can use pev2 Show archive.org snapshot , a handy tool for analyzing execution plans. You can download a standalone HTML file Show archive.org snapshot to use the app offline—simply open the file in your browser and paste your query plans.