Posts

Showing posts with the label ast

Resolve N+1 Query Problem

Image
Introduction N+1 Query Problem is a performance issue that occurs when an application executes 1 initial query to fetch a list of N records and then executes N additional sub-queries to fetch related data for each record. The total number of queries sent to the Database will be N + 1 . As N increases (for example N = 1000), the application must execute 1001 SQL statements, causing an I/O bottleneck , increasing latency and overloading the Database . Example Suppose you need to display 10 products (N = 10) along with the list of variants for each product: First Query (1): Get the list of 10 products: SELECT * FROM products LIMIT 10 Next N Queries (N = 10): Iterate through each product to get variants. SELECT * FROM product_variants WHERE product_id = 1 ; SELECT * FROM product_variants WHERE product_id = 2 ; ... SELECT * FROM product_variants WHERE product_id = 10 ; Total: 10+1=11 SQL queries. If fetching 1,000 products, the number of queries spikes to 1,001 SQL ...