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

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

Transcript

Your page makes a hundred trips to the database when one would do. This is the N plus one problem. Your code fetches a list, then asks the database again for every item on it. A hundred items means a hundred and one trips. Every trip costs time, a connection and database work, and that means electricity. GreenCode researchers list the N plus one query among the worst energy wasters in code. Here is the fix you can use today. Ask for everything in one go, with a join or one batched query. Many database libraries can load the related data for you, if you ask. Now it is two trips, not a hundred and one. So check any loop that has a database call inside it. GreenCode's Constitution skill can help an AI coding agent spot and fix these. Then see which program draws the power, using tools like Scaphandre. GreenCode helps tackle this by checking code for quality, security and energy waste together. Wasteful calls like these come out as ranked defects, beside bugs and security issues. That was GreenCode Tech Tip number one. Follow for the next tip, and find more on greencode.ai/tech-tips.

All GreenCode Tech Tips · All GreenCode videos

  • Tip #1
  • For Developers
  • Length 1:12
  • Category Databases, APIs and storage
GreenCode

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

Get in touch