Course contentsShow
← Node.js
Lesson 806 of 1,9808. Data Persistence and ORM IntegrationFree lesson

Querying with Joins and Includes

You will build complex queries across multiple related tables using ORM syntax.

Mastering Complex Data Retrieval with Joins and Includes

In this lesson, you will learn how to bridge multiple database tables in a single query using ORM-specific syntax to retrieve related data efficiently.

When working with relational databases, your data is often spread across several tables (e.g., Users, Posts, and Comments). While previous lessons taught you how to define these relationships (One-to-Many or Many-to-Many), Querying with Joins and Includes is how you actually fetch that linked information without writing manual SQL.

Eager Loading with include

The most common way to handle related data is through "Eager Loading." When you query a model, you instruct the ORM to fetch associated records at the same time. This is effectively an INNER JOIN or LEFT OUTER JOIN handled by the ORM engine.

Consider a scenario where you want to fetch all users along with their recent blog posts. Instead of running two separate queries, you use an include statement:

const users = await User.findAll({
  include: [{
    model: Post,
    where: { status: 'published' } // Filtering the join
  }]
});

Complex Joins

Sometimes, you need to filter the main result set based on properties found in a related table. By using include with a where clause, the ORM performs a join under the hood. This ensures that you only get back users who actually have published posts. If you omitted the where clause inside the include, the ORM would perform a LEFT JOIN, returning all users even if they have zero posts.

Why this matters

Using joins via include is significantly more performant than "Lazy Loading," where you might accidentally trigger the "N+1 query problem" (running a separate database hit for every single record in a loop). By specifying your requirements upfront in the query, you allow the database to optimize the execution plan, retrieving the entire object graph in one efficient round trip.

Key Takeaway: Use include to perform joins within your ORM queries, allowing you to fetch complex, multi-table data structures in a single, performant operation.