Tech Tip #1: Stop the N+1 query

Your page makes a hundred trips to the database when one would do.

Video created by explainapaper.com

Open full video page with the transcript

The problem

Code fetches a list, then asks the database again for every item on it. A hundred items means a hundred and one round trips, each with its own connection work and query planning. Every query is fast on its own, so the pattern hides in plain sight.

The fix you can use today

  • Fetch the related rows in one go: a join, or one batched lookup with IN (...).
  • Ask your ORM to load related data eagerly (select_related / prefetch_related, JOIN FETCH, include).
  • Check every loop that has a database call inside it.

GreenCode researchers list the N+1 query among the worst energy wasters in code.

Tools that help

  • GreenCode Constitution skill (GreenCode researchers): open-source energy principles and a catalogue of 37 energy anti-patterns that an AI coding agent can follow to find and fix waste like this
  • Django Debug Toolbar: lists every SQL query a request made, so repeated queries in a loop stand out
  • Scaphandre: measures the power drawn by each process on a Linux server and exports it to Prometheus and other monitoring stacks

How GreenCode helps

GreenCode helps tackle this by checking code for quality, security and energy waste in one pass. Wasteful calls like these come out as ranked defects, alongside the bugs and security findings. More on this.

Tags

#sql#orm#databases#loops

Sources

All GreenCode Tech Tips

  • Tip #1
  • For Developers
  • Category Databases, APIs and storage
  • Format short video
GreenCode

Want this checked on your own system? Talk to the GreenCode team.

Get in touch