Good day, There can be several reasons for the server to spill to the tempdb and the solution is according to these. Here some options for example but for full tutorial it is recommend to search for blogs/articles as we cannot write a full blog here in a forum's response :-) SQL Server spills data to TempDB when the query was not granted enough memory to finish the operation. So the question is why he query was not granted enough memory (1) Maybe your server does not have enough memory RAM? Check memory pressure and if needed add more memory or configure the server to use more memory if available in the machine. (2) In many cases the server have the available memory but it does not allocate it to the execution of the query. (2.1) This can be a result of wrong statistics Execute the following queries to monitor the statistics of the table and the real number of rows (compare the number of "rows" in first query to the number of rows you COUNT in the second one DBCC SHOW_STATISTICS ('', ) SELECT COUNT(*) from
update the statistics so the server will have the best information about the amount of rows UPDATE STATISTICS
WITH FULLSCAN (2.2) This can be a result of using a "black box" like using User Defined Function (UDF), it is very common using SQLCLR function/SP - in these cases the server might not be able to estimate the amount of memory it will need and it. (3) Build indexes in a correct manner. (4) Adjust query as possible. A complex queries can lead to wrong estimation, for example with multiple JOIN, multiple range scans (BETWEEN), multiple Parallelism operators, These action might help: Omit the ORDER BY clause, eliminate the column that participates in range scans from the `ORDER BY`, Force serial execution `MAXDOP = 1`, using the hints `ONLINE = ON, SORT_IN_TEMPDB = ON`, writing the data to a heap temp table first, and more... Well.... these are some starting points... HIGHLY recommended to keep learning the topic with full articles on the topic Hope this is useful :-)