Subquery makes complet code very slow

Hans Furmann 40 Reputation points
2024-02-24T16:15:05.8866667+00:00

Hello, I have the following query that uses another query. As I understand the runtime behavior, this second query is called again every time the main query creates a new record. Both queries are actually quite fast. Unfortunately, the overall construct becomes very slow when I call them together. Can someone tell me how I can avoid unnecessary re-iteration of the subquery? Example

With X1 As
(
	SELECT COUNT(Employee_ID) As NumberOfEmployees, 
	TBL_Employees
)
SELECT MyTable1.MyField1, MyTable3.MyField2, X1.NumberOfEmployees, X1.EntryDate
FROM MyTable1 INNER JOIN MyTable3 ON MyTable1.MyField5 = MyTable3.MyField4 CROSS JOIN X1

Query X1 needs less then 1 second also the main Query does if I eleminate query X1 of it.
It seems X1 runs wich each record the main query delivers.
Any idea how I can speed up this query?

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
13,203 questions
SQL Server Transact-SQL
SQL Server Transact-SQL
SQL Server: A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.Transact-SQL: A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
62 questions
{count} votes

Accepted answer
  1. Erland Sommarskog 105.8K Reputation points MVP
    2024-02-24T16:49:57.22+00:00

    First of all, the query you posted is not correct. The CTE selects two columns, but there is no FROM clause. It seems that in your ambition to mask the table and column names, you managed to distort the query.

    I can make the guess that the command in the CTE is supposed to be FROM, and in that case, the simple answer would be: Save the count in a variable and skip the CTE.

    If that was not the correct answer, post your actual query without modification. Alternatively, copy the database, rename table and colunm names and run the altered query to make sure that it has the behaviour you describe.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful