Writing
Don’t Stop Paying Attention to SQL Query Performance
ORMs make queries easy to write but not cheap to run. Find the queries that cost the most, read their plans, fix N+1 patterns and missing indexes, and test with production-sized data.
By Ka Lun Chan · Architecture / Engineering judgment
Do you still need to watch SQL performance when an ORM writes your queries?
Yes. An ORM makes queries easy to write, but it doesn’t make them cheap to run, and the expensive ones usually only show up once production data grows. Measure which queries take the most total time, read their plans, fix N+1 patterns and missing indexes, and keep checking after every release.
I first wrote this on my old blog. This version keeps the advice that held up and replaces a product pitch with a playbook you can run against your own database today.
The practical loop has five steps:
- Find the queries that cost the most in aggregate, using
pg_stat_statementson PostgreSQL or the slow query log and Performance Schema on MySQL. - Read the plan with
EXPLAIN (ANALYZE, BUFFERS)before changing anything. - Fix the common ORM pattern first: N+1 queries.
- Add indexes deliberately, remembering that each one slows writes a little.
- Test with production-sized data, and compare query stats before and after each deploy.
| Symptom | Likely cause | How to confirm |
|---|---|---|
| A list page gets slower as the list grows | N+1 queries: one query per row for an association | Count queries per request in the log; turn on strict loading or lazy-loading prevention |
| One query is slow and the plan shows a sequential scan on a big table | Missing or unusable index for the filter or sort | EXPLAIN (ANALYZE, BUFFERS): look for many rows removed by the filter |
| Fast in development, slow in production | Small development data, so the planner and the code take a different path | Run the same EXPLAIN against a production-sized copy |
| Estimated rows are far from actual rows | Stale or missing planner statistics | Compare estimated and actual rows per plan node; run ANALYZE on the table |
| Fine before a release, slow after it | A new or changed query, or a new access pattern | Compare pg_stat_statements or digest totals before and after the deploy |
| Writes slowed down after an indexing push | Every extra index has to be maintained on each insert and update | Check write latency and which indexes are never scanned |
Why do slow queries get missed in ORM-based apps?
Because the ORM makes database access feel like ordinary method calls, and development databases are too small to make bad queries hurt. The cost arrives later, in production, where it’s harder to trace back to the line of code that caused it.
Earlier in my career I hand-coded SQL for Python and PHP applications. Analyzing slow queries back then was tedious, and measuring their performance took a lot of time. Frameworks like Yii, Laravel and Rails’ Active Record changed that. Writing data access went from a chore to something fun and easy, and we were having so much fun building the application that it was easy to forget about slow queries.
Slow applications hurt user experience, engagement, conversion and revenue, so the problem doesn’t stay with engineering. When it hits, the DBA, the development team and the operations team all try to isolate the cause, and each looks from their own view: the DBA sees an expensive statement, developers see a clean-looking model method, ops sees CPU and I/O on the database host. Getting those views to meet on a root cause can take a long time, and there may be more than one problem.
Most applications built against a small dataset run smoothly in development. Once they’re rolled out to production, all bets are off, because the database keeps growing. A query that scanned a few hundred rows on a laptop can scan millions once the tables fill up. This is one of the costs I wrote about in the hidden cost of software architecture: decisions that are free on day one and expensive at scale.
How do you find the slow queries?
Let the database tell you. On PostgreSQL, the pg_stat_statements extension aggregates execution statistics for every normalized query. On MySQL, the slow query log captures statements over a time threshold and the Performance Schema summarizes statements by digest.
Sort by total time first, not by the single slowest query. A 5 ms query called 200,000 times an hour usually matters more than a 3 second report that runs once a day. pg_stat_statements needs to be preloaded, which means a restart, and then created in each database where you want the view:
-- postgresql.conf (needs a restart):
-- shared_preload_libraries = 'pg_stat_statements'
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
-- Where the database spends its time, most expensive first
SELECT query,
calls,
round(total_exec_time::numeric, 1) AS total_ms,
round(mean_exec_time::numeric, 2) AS mean_ms,
rows,
100.0 * shared_blks_hit
/ nullif(shared_blks_hit + shared_blks_read, 0) AS hit_percent
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;The hit_percent column is the share of blocks served from shared buffers, which hints at whether a query is reading from memory or from disk. Reset the stats with pg_stat_statements_reset() when you want a clean baseline, for example just before a release.
On MySQL, the slow query log is off by default and long_query_time defaults to 10 seconds, which is far too high for a web request. Turn it on with a lower threshold, then summarize the file with mysqldumpslow. For an always-on view without log files, query performance_schema.events_statements_summary_by_digest, which groups statements by their normalized form the way pg_stat_statements does.
How do you read a query plan?
Run EXPLAIN (ANALYZE, BUFFERS) on the query and compare what the planner expected with what happened: estimated rows against actual rows, time per node, and how many blocks came from cache or disk. The node where those diverge is usually where the problem is.
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;
-- ANALYZE really runs the statement, so test writes inside a rollback
BEGIN;
EXPLAIN (ANALYZE, BUFFERS)
UPDATE orders SET status = 'archived'
WHERE created_at < now() - interval '1 year';
ROLLBACK;Three things to look for. A sequential scan on a large table with many rows removed by the filter usually means a missing or unusable index. Estimated rows that are wildly off from actual rows point at stale statistics, which ANALYZE on the table refreshes. A nested loop that runs thousands of times often means the planner guessed a small row count and was wrong.
ANALYZE executes the statement, so wrap anything that writes in BEGIN and ROLLBACK. In recent PostgreSQL versions buffer counts are included automatically with ANALYZE. Older versions need BUFFERS spelled out, so writing it explicitly works everywhere. MySQL has its own EXPLAIN ANALYZE, which also runs the query and prints a tree of estimated and actual costs.
What is an N+1 query, and how do you fix it?
It’s one query to load a list and then one more query per item to load an association, so ten books cost eleven queries and a thousand cost a thousand and one. Every major ORM has an eager-loading method that collapses it to one or two queries, and a strict mode that raises an error when you forget.
# N+1: one query for the books, then one more per book for its author
Book.limit(10).each { |book| puts book.author.last_name }
# Fixed: two queries in total, however many books there are
Book.includes(:author).limit(10).each { |book| puts book.author.last_name }
# Catch the next one early (config/environments/development.rb and test.rb):
# lazy loading an association raises ActiveRecord::StrictLoadingViolationError
config.active_record.strict_loading_by_default = trueRails offers includes, which picks a strategy for you, plus preload for separate queries and eager_load for a single join. Django uses select_related for foreign keys and one-to-one relations, which joins in SQL, and prefetch_related for many-to-many and reverse relations, which runs a second query and joins in Python. Laravel uses with(), and Model::preventLazyLoading(! $this->app->isProduction()) in AppServiceProvider throws a LazyLoadingViolationException outside production. Laravel also has automatic eager loading, which its docs still mark as beta.
Turning on strict mode in development and tests is the habit that pays off most, because it turns a silent performance problem into a failing test. For Rails, the bullet gem I cover in the Ruby gems I use adds N+1 and unused eager-loading warnings on top.
Should you just add more indexes?
Add the indexes your measured slow queries need, and no more. Every index has to be kept in sync with the table on each insert, update and delete, so unused indexes slow writes and take space without speeding anything up.
PostgreSQL’s documentation is direct about it: indexes add overhead to data manipulation, can prevent heap-only tuple updates, and should be removed if they’re rarely or never used. Its statistics views count scans per index, which makes unused ones easy to spot. Match the index to the query: the columns in the WHERE clause first, then the sort column if the query orders and limits. Check the plan again afterwards to confirm the planner actually uses it.
Indexes are only one fix. Rewriting the query, selecting fewer columns, paginating, or caching results can matter more. I cover caching in database performance and caching. That’s also where the original version of this post finished.
How do you keep queries fast after launch?
Test against data that looks like production in size and shape, and treat query performance as something you check on every release, not once. Most regressions come from a new query or a changed access pattern, and the stats will show them if you look.
- Keep a production-sized dataset for performance testing: a masked copy, or generated data with realistic row counts and distributions. Ten rows per table hides almost every problem in this post.
- Run
EXPLAIN (ANALYZE, BUFFERS)on new queries against that dataset during review, not after the deploy. - Snapshot
pg_stat_statementsor the MySQL digest table before a release and compare the top queries after it. - Give the DBA, developers and ops the same view of query timings, so a slowdown starts with shared evidence instead of three separate theories.
Naming and schema choices feed into this too. Consistent table and key names, as I wrote in plural or singular API and table names, make the queries in your stats easier to map back to the code that produced them.
Sources
Checked in November against the PostgreSQL documentation for pg_stat_statements, EXPLAIN and indexes, the MySQL reference manual for the slow query log, statement digests and EXPLAIN ANALYZE, and the Rails, Django and Laravel documentation on eager loading. The symptom table, the examples and the recommendations are mine.
- PostgreSQL Docs: pg_stat_statements
- PostgreSQL Docs: EXPLAIN
- PostgreSQL Docs: Indexes introduction
- MySQL 8.4 Reference Manual: The Slow Query Log
- MySQL 8.4 Reference Manual: Performance Schema Statement Digests
- MySQL 8.4 Reference Manual: EXPLAIN and EXPLAIN ANALYZE
- Ruby on Rails Guides: Active Record Query Interface (eager loading, strict_loading)
- Django Docs: QuerySet API (select_related, prefetch_related)
- Laravel Docs: Eloquent Relationships (eager loading, preventing lazy loading)
Short answers
Do I need to worry about SQL performance if I use an ORM?
Yes. An ORM makes queries easy to write but not cheap to run, and the expensive ones usually appear only once production data grows. Measure which queries take the most total time, read their plans, and fix N+1 patterns and missing indexes.
How do I find slow queries in PostgreSQL or MySQL?
On PostgreSQL, preload the pg_stat_statements extension and sort its view by total_exec_time. On MySQL, enable the slow query log with a lower long_query_time than the 10 second default, or query the Performance Schema statement digest summary table.
What is an N+1 query?
One query loads a list, then one more query runs for each item to load an association. Fix it with eager loading: includes or preload in Rails, select_related or prefetch_related in Django, and with() in Laravel. Strict loading in Rails and preventLazyLoading in Laravel raise an error when it happens.
Should I add an index for every slow query?
Only for the queries you have measured, and confirm the plan uses it. Each index must be updated on every insert, update and delete, so unused indexes slow writes. PostgreSQL recommends removing indexes that are seldom or never used.
Start with one query
Turn on pg_stat_statements or the slow query log this week, take the top query by total time and read its plan. That one query usually shows you which of these fixes your app needs first.