CodexBloom - Programming Q&A Platform

SQL Server 2017: Query performance guide with large dataset and multiple subqueries

👀 Views: 85 💬 Answers: 1 📅 Created: 2025-06-12
sql-server performance optimization sql

I'm relatively new to this, so bear with me. I need some guidance on I'm converting an old project and I'm a bit lost with Quick question that's been bugging me - I'm experiencing important performance optimization with a query in SQL Server 2017 that involves multiple subqueries. The dataset has grown to over 3 million records, and I'm trying to retrieve aggregated sales data while filtering based on specific conditions. Here's the query I am using: ```sql SELECT s.StoreID, s.StoreName, (SELECT SUM(o.TotalAmount) FROM Orders o WHERE o.StoreID = s.StoreID AND o.OrderDate >= '2023-01-01') AS TotalSales, (SELECT COUNT(*) FROM Orders o WHERE o.StoreID = s.StoreID AND o.OrderDate >= '2023-01-01') AS OrderCount FROM Stores s WHERE s.IsActive = 1; ``` While it works correctly, the execution time is over 15 seconds, and I need to optimize it. I have already tried creating indexes on the `Orders` table for `StoreID` and `OrderDate`, but it hasn’t made a important difference. I also considered using JOINs instead of subqueries but was unsure how to rewrite the query effectively. When I profile the query, I see that most of the time is spent on the subqueries. I get the following execution plan warning: *'Missing Join Predicate'*. Could this be an indicator of what I'm doing wrong? Additionally, the estimated number of rows is significantly lower than the actual number returned, leading me to suspect that SQL Server's cardinality estimation might be part of the question. Is there a way to refactor this query to improve performance, possibly using common table expressions (CTEs) or a different approach? Any insights or best practices would be greatly appreciated! What's the best practice here? My team is using Sql for this REST API. I'd really appreciate any guidance on this. For reference, this is a production microservice. Could this be a known issue? The stack includes Sql and several other technologies. What's the correct way to implement this?