From 597505de2cdb8279bdcf26a9ea4ccfc5036c96d8 Mon Sep 17 00:00:00 2001 From: Matt Quinn Date: Mon, 26 Jun 2023 16:31:16 -0400 Subject: [PATCH] Clarify that N+1s also apply to modifications (#7220) A customer brought up that we detect N+1s on SQL queries that make modifications (e.g. INSERT, UPDATE, DELETE) and not just SELECT, even though our docs only reference the SELECT case. Add a note to the intro clarifying that modifications are also detected, and add an example of an INSERT N+1 with fix. Co-authored-by: vivianyentran <20403606+vivianyentran@users.noreply.github.com> --- .../performance-issues/n-one-queries.mdx | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/src/docs/product/issues/issue-details/performance-issues/n-one-queries.mdx b/src/docs/product/issues/issue-details/performance-issues/n-one-queries.mdx index 9a709a9d26760..2dadf1d3dc93c 100644 --- a/src/docs/product/issues/issue-details/performance-issues/n-one-queries.mdx +++ b/src/docs/product/issues/issue-details/performance-issues/n-one-queries.mdx @@ -6,7 +6,7 @@ redirect_from: description: "Learn more about N+1 queries and how to diagnose and fix them." --- -_N+1 queries_ are a performance problem in which the application makes database queries in a loop, instead of making a single query that returns all the information at once. Each database connection takes some amount of time, so querying the database in a loop can be many times slower than doing it just once. This problem often occurs when you use an object-relational mapping (ORM) tool in web frameworks like Django or Ruby on Rails. +_N+1 queries_ are a performance problem in which the application makes database queries in a loop, instead of making a single query that returns or modifies all the information at once. Each database connection takes some amount of time, so querying the database in a loop can be many times slower than doing it just once. This problem often occurs when you use an object-relational mapping (ORM) tool in web frameworks like Django or Ruby on Rails. ## Detection Criteria @@ -64,3 +64,18 @@ def books(request): Django will `JOIN` the tables ahead of time, and preload the author information. That way, calling `book.author.name` does not need to make an extra query. Instead of a long waterfall, there is a single `SELECT` query: ![Solved N+1 queries in an example application](n-plus-one-queries-after.png) + +N+1s can also happen when modifying data. For example, instead of creating objects in a loop: + +```python +for i in range(1, 11): + Book.objects.create(title: f"Book {i}") +``` + +You can instead create the objects in a single query: + +```python +Book.objects.bulk_create( + [Book(title: f"Book {i}") for i in range(1, 11)] +) +```