BackendQuestion 32 of 52
Solving N+1 with Eager Loading
Problem
Your ORM is slowing down the application because it runs one query to fetch 100 employees, and then 100 separate queries to fetch their department names. Your senior developer suggests fixing the N+1 query problem by doing it in one database call. Join employees and departments to get the first_name and department_name in a single query.
Database Schema
Table: employees
employee_id(INT): Unique identifier for the employee.first_name(VARCHAR): First name of the employee.last_name(VARCHAR): Last name of the employee.salary(INT): Employee's salary.department_id(INT): Foreign key referencing the department.manager_id(INT): Foreign key referencing the manager (another employee).hire_date(DATE): Date the employee was hired.
Table: departments
department_id(INT): Unique identifier for the department.department_name(VARCHAR): Name of the department.
Try It
Loading playground environment...