DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Data Engineering
  3. Databases
  4. Common Table Expression, Just a Name

Common Table Expression, Just a Name

Common Table Expression (CTE) is a bit of a misnomer because it's not a table but rather a query. It straightforward to declare and easy to use with another queries. If you're not familiar with CTE this is worth a quick look.

Grant Fritchey user avatar by
Grant Fritchey
·
Jul. 26, 16 · Tutorial
Like (5)
Save
Tweet
Share
3.55K Views

Join the DZone community and get the full member experience.

Join For Free

the common table expression (cte) is a great tool in t-sql. the cte provides a mechanism to define a query that can be easily reused over and over within another query. the cte also provides a mechanism for recursion which, though a little dangerous and overused, is extremely handy for certain types of queries. however, the cte has a very unfortunate name. over and over i’ve had to walk people back from the “table” in common table expression. the cte is just a query. it’s not a table. it’s not providing a temporary storage space like a table variable or a temporary table. it’s just a query. think of it more like a temporary view, which is also just a query .

every time i explain this, there are people who don’t believe me. they point to the “table” in the name, “see. says so right there. it’s a table.”

it’s not and i can prove it. let’s create a relatively simple cte and use it in a query:

with    mycte
          as (select    c.customername,
                        cc.customercategoryname
              from      sales.customers as c
              join      sales.customercategories as cc
              on        cc.customercategoryid = c.customercategoryid
              where     c.customercategoryid = 4)
    select  *
    from    mycte;


now, i’m going to run the query within the cte and the cte together as two statements in a batch and capture the execution plans:

execplans

on the top, the cte, on the bottom, the query. you’ll note that the execution plans are identical. they each have the exact same query plan hash value in the properties, 0x88efd2b7c165e667, even though they have different query hash values, 0x192ffc125a08cc35 and 0xfeb7f2bcac853cd5, respectively. further, if i capture the query metrics using extended events, i get identical reads and, on average, identical execution times:

duration

this is because, there is no table being created. the data is not treated differently. a cte is just a query, not some type of temporary storage.

heck, let’s do one more thing. let’s use the latest ssms plan comparison tool and highlight one of the operators to see what differences there are internally in the plan:

plancompare

i don’t see a lot of differences. in fact, i don’t see any. that’s because the optimizer recognizes these two queries as identical. if it was loading data into temporary storage, you would see differences in something. we don’t. this is because, despite the somewhat unfortunate emphasis that gets placed on the table portion of the name, the emphasis of the name, common table expression, should be on the word expression.

i will point out an interesting difference, especially useful for those who plug in ctes everywhere, whether it’s needed or not. let’s look at the properties of the two plans:

peroperties

you can see the similarities and differences that i pointed out earlier in the statement, query hash and query plan hash, as well as the estimated subtree cost and others. what’s truly interesting is that the compilecpu, compilememory and compiletime for the cte is higher than the regular query. while the cte is just a query, it’s a query that adds a non-zero overhead when used, and therefore, should only be used where appropriate (good gosh, i’ve seen people put it everwhere, on every single query, don’t do that).

hopefully, this is enough to establish, truly, completely, and thoroughly, that the common table expression is an expression, not a table.

yeah, i did this before , but it keeps coming up, so i tried a different approach. let’s see if the word gets out. your common table expression is not a table.

i love talking about execution plans and query tuning. i’ll be doing this at an all day pre-con at sqlserver geeks annual summit in bangalore india.

Database

Published at DZone with permission of Grant Fritchey, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • gRPC on the Client Side
  • Building a REST API With AWS Gateway and Python
  • What Are the Different Types of API Testing?
  • Cloud Performance Engineering

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: