Skip to content

Commit

Permalink
Clarify that N+1s also apply to modifications (#7220)
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
mjq and vivianyentran committed Jun 26, 2023
1 parent 15392c5 commit 597505d
Showing 1 changed file with 16 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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)]
)
```

1 comment on commit 597505d

@vercel
Copy link

@vercel vercel bot commented on 597505d Jun 26, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

sentry-docs – ./

docs.sentry.io
sentry-docs.sentry.dev
sentry-docs-git-master.sentry.dev

Please sign in to comment.