ENGINEERING NOTE / 13 SQL SERVERPERFORMANCE

A CTE Is Not a Temp Table

Anonymous searches on a public site took 13 seconds on average and caused almost every query timeout on the server. The search itself was not the problem. Writing it once and reading it four times was.

8 MIN READ

PERFORMANCEQUERY-TUNINGCTEFULL-TEXT-SEARCHDYNAMIC-SQL

TABLE OF CONTENTS
  1. How the query is built
  2. Four searches, not one
  3. The fix, and the three versions before it
  4. The order was never defined
  5. Results on staging
  6. What carries over

The same SQL Server instance as the scalar UDF note hosts a few thousand single-tenant databases, and one list procedure runs in all of them. Most of its calls are cheap. One shape was not: an anonymous visitor typing words into the public search box.

A week of Query Store across every database put numbers on it. About 32,000 anonymous searches, in more than a thousand tenant databases, averaging 13.1 seconds each. Logged-in users ran about 4,900 searches in the same week at 1.0 second on average. The application gives up at 120 seconds, and of the 1,336 query timeouts on the whole server that week, 1,312 were anonymous searches.

SHARE OF SERVER CPU
13.8%
SHARE OF LOGICAL READS
55.6%
SHARE OF TIMEOUTS
98%
AVERAGE DURATION
13.1 s

A day of Extended Events agreed. Of the calls to the procedure that took two seconds or more, 97% were anonymous searches sorted by relevance, with search terms and the public site’s visibility filters.

How the query is built§

The procedure assembles its statement as dynamic SQL. When there are search terms, it writes the search as a common table expression: full-text matches from six sources combined with UNION ALL, grouped by item, joined to the item list and to a permission cache. Then it applies the filters the caller asked for. The public site always asks for some: hide items flagged as private, hide items not yet published, and so on.

The filters come from a shared generator function that is told the name of the CTE, and it writes each filter as a subquery against it. Renamed and trimmed, the generated statement looked like this:

;WITH Matches (ItemId, CanView, OrderValue) AS (
    SELECT DISTINCT i.ItemId, p.CanView, s.Rank
    FROM   Content.Items AS i
    JOIN   Security.PermissionCache AS p ON ...
    JOIN  (SELECT ItemId, SUM(Rank) AS Rank
           FROM ( ... six CONTAINSTABLE sources, UNION ALL ... ) AS hits
           GROUP BY ItemId) AS s ON s.ItemId = i.ItemId
    WHERE  ...
)
INSERT INTO @Results (ItemId, RowNumber, CanView)
SELECT DISTINCT m.ItemId,
       ROW_NUMBER() OVER (ORDER BY m.OrderValue DESC),
       m.CanView
FROM   Matches AS m
WHERE  m.ItemId IN (SELECT m2.ItemId FROM Matches AS m2
                    LEFT JOIN Content.ItemFlags AS f
                           ON f.ItemId = m2.ItemId AND f.FlagId = 101 AND f.Value = 1
                    WHERE f.ItemId IS NULL)
  AND  m.ItemId IN (SELECT m2.ItemId FROM Matches AS m2 ... FlagId = 102 ...)
  AND  m.ItemId IN (SELECT m2.ItemId FROM Matches AS m2 ... FlagId = 103 ...);

Read as a person reads it, that is one search and three cheap checks against its result. That is not how SQL Server reads it.

Four searches, not one§

A CTE in SQL Server is not stored and reused. It is a named subquery, and the optimizer expands its definition into every place it is referenced. Three filters plus the outer FROM is four references, so the production plans contained the whole search four times: six full-text sources, the permission cache and the item list, each time.

That alone would make the call roughly four times as expensive. What made it catastrophic was the estimate. After the search joins, the optimizer expected one row. With one row on the outer side, a nested-loop semi join is the cheapest way to apply each filter, so it chose nested loops, and the inner side of each loop was a copy of the search. In practice there were thousands of candidate items, so the full-text matching ran again for every one of them.

OBSERVED What the production plans showed
search copies in the plan           4  (one per CTE reference)
estimated rows after the search     1
join strategy for the filters       nested-loop semi joins over the search
estimated plan cost                 about 5-6.5   (judged trivial)
optimizer                           timed out before finishing
parallelism                         none: results go into a table variable

Every part of that is a consequence of the first line. The optimizer timed out because the expanded tree was large. It costed the plan as trivial because it believed one row. And it could not go parallel to soften any of it, because the insert target was a table variable.

The anonymous searches were the slow ones because the public site always sends its visibility filters, and the filters are what reference the CTE. Of about 37,100 searches in the week, all but two carried them, including every one that timed out.

The fix, and the three versions before it§

The obvious remedy is to evaluate the search once, into a temporary table with real statistics and an index, and let the filters read that. Getting there without changing anything else took four attempts.

v1 materialised the search into #Candidates and passed that name to the filter generator instead of the CTE’s name. It was fast. It also changed the text the generator produced for grouped filters, which build their SQL a different way, and broke them.

v2 left the filter SQL alone. A placeholder after the CTE is replaced, once the filters are known, with three statements that materialise the CTE and then redefine the same name over the temp table:

SELECT * INTO #Candidates FROM Matches;
CREATE CLUSTERED INDEX IX_Candidates_ItemId ON #Candidates (ItemId);
;WITH Matches AS (SELECT * FROM #Candidates)
-- the INSERT ... WHERE m.ItemId IN (SELECT ... FROM Matches ...) follows unchanged

The generated filters still say Matches, and now Matches is a cheap read of an indexed table. But v2 did this whenever there were filters, and a list call with filters and no search got slower: one test case went from 0.8 s of CPU to 2.1 s. Without a search the CTE is cheap, and copying it into a temp table is pure overhead.

v3 only materialises when the call has search terms and filters. Every other call gets the original statement, byte for byte:

SET @Statement = REPLACE(@Statement, N'/*#CANDIDATES#*/',
    CASE WHEN LEN(@FilterSql) > 0 AND LEN(ISNULL(@SearchTerms, N'')) > 0
         THEN N'SELECT * INTO #Candidates FROM Matches ...'
         ELSE N'' END);

v3 returned the same rows as the original in every case. In ten cases it did not return them in the same order, which is where the fourth version came from.

The order was never defined§

The result is numbered with ROW_NUMBER() OVER (ORDER BY <sort>), and when two items have the same sort value, nothing decides which comes first. Every one of the 6,965 positions that differed across those ten cases was checked against the computed sort key: in each, the items swapped had exactly the same value. One of the ten ran the original SQL unchanged in both versions and still came back in a different order, which settles it. The original was non-deterministic for ties all along. A different plan just exposed it.

v4 adds the item id as a tiebreaker whenever a sort column is used:

ROW_NUMBER() OVER (ORDER BY m.OrderValue DESC, m.ItemId ASC)

Across three rounds of every case, v4’s order was identical each time, and spot checks against full-precision sort keys found no violations. The tiebreaker cost 0.8% more CPU than v3, which is within run-to-run noise. The visible effect is that tied items now always come back lowest id first, and that went into the handover for the application team.

Results on staging§

First, the production shape itself, on one staging copy of a tenant database, four runs of each version with the same parameters:

RESULT Production search shape, one staging database, 4 runs each
duration           logical reads
original           240-252 s          251.1M every run
v4                 0.8-0.9 s          120.8k

Then 46 cases against the same database: 15 from a parameter matrix and 31 distinct call shapes replayed from the production trace. Two of the matrix cases fail on both versions with the same syntax error, a pre-existing bug in the grouped-filter generator, and were reported separately. In the other 44, the original and the tuned version returned the same rows and values, with order differing only between ties.

CPU
983.8 s → 28.2 s
LOGICAL READS
818.3M → 3.06M
CASES SLOWER ON CPU
0

One case got more expensive on reads, and it is a real trade-off rather than noise. A search whose extra filter matches nothing lets the original stop early: about 1,000 reads and 0.3 s. The tuned version runs the search first and then finds nothing, about 56,000 reads and 0.5 s. Still well inside any reasonable budget.

Last, nine of the ten largest staging databases, with the tuned procedure created alongside the original under another name, every case compared, and the copy dropped afterwards:

RESULT 64 cases that finished on both versions, nine staging databases
original        tuned
CPU               6,407 s         57.9 s
duration          7,106 s         135 s
logical reads     5.17B           15.5M

calls without a search (original SQL path), 24 cases:
CPU               19.9 s          19.0 s

The last two lines matter as much as the first three. The calls that were not supposed to change did not.

One case is still open. An administrator search timed out on both versions in two of the databases, immediately after a cancelled run of the original; in two others the same case took 2.5 to 3.2 seconds. It has to be re-run on its own, with waits and blocking captured, before this goes anywhere near production.

What carries over§

The fix is three lines of generated SQL. Finding the reason for it was the work:

  1. Count the references, not the CTEs. A CTE used once is free. A CTE used four times is four subqueries, and if one of them is a full-text search, the cost multiplies before the optimizer has made a single bad choice.
  2. Look for the estimate that justifies the loop. The repeated work was bad; the one-row estimate turned it into repeated work per row.
  3. Materialise only where it pays. The temp table is right when the CTE is expensive and read several times, and wrong when it is cheap. The condition in v3 is the difference between a fix and a new regression.
  4. Leave everything else byte for byte. Calls that take the original path run the original text, which is what made it possible to say they did not change, rather than hope.
  5. Treat a changed order as a question. Here the answer was an undefined order in the original, and the fix was to define it.

A CTE reads like a variable. It behaves like a macro. Most of the time the difference does not matter; here it was 98% of the server’s timeouts.