0

How can I measure the CTE execution time? I want to be able to log the time between CTEs. E.g like this :

--log time here 1 -> insert into log(...) values(...)

WITH cte1
AS (
    SELECT 1 AS id
    )
    --log time here 2-> insert into log(...) values(...)
    ,cte2
AS (
    SELECT 2 AS id
    )

--log time here 3-> insert into log(...) values(...)

SELECT *
FROM cte1

UNION ALL

SELECT *
FROM cte2
chosenOne Thabs
  • 1,480
  • 3
  • 21
  • 39

1 Answers1

3

CTEs do not run as separate queries. The entire query is optimized and run as a single entity.

Some databases tend to materialize CTEs (that is, store the results as temporary tables). Other databases tend to incorporate them into execution plans where they are referenced.

However, nothing requires that CTEs run separately. So, if you want an estimate of the length of time, just run the CTE as a separate query.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786