{"id":16062,"date":"2025-09-19T06:36:41","date_gmt":"2025-09-19T06:36:41","guid":{"rendered":"https:\/\/www.kaashivinfotech.com\/blog\/?p=16062"},"modified":"2025-09-19T06:36:41","modified_gmt":"2025-09-19T06:36:41","slug":"common-table-expression-cte-in-sql","status":"publish","type":"post","link":"https:\/\/www.kaashivinfotech.com\/blog\/common-table-expression-cte-in-sql\/","title":{"rendered":"Common Table Expression (CTE) in SQL: 7 Lessons That Changed How I Write Queries"},"content":{"rendered":"<h2><strong>What is a Common Table Expression (CTE) in SQL?<\/strong><\/h2>\n<p>Let\u2019s keep it real. <span aria-haspopup=\"dialog\" aria-expanded=\"false\" aria-controls=\"radix-_r_1n_\" data-state=\"closed\">When I first encountered the term common table expression I immediately thought, \u201cAnother <a href=\"https:\/\/www.kaashivinfotech.com\/sql-server-course-in-chennai\/\">SQL<\/a> term?<\/span> <span aria-haspopup=\"dialog\" aria-expanded=\"false\" aria-controls=\"radix-_r_1o_\" data-state=\"closed\">And do not we already have subqueries and temp tables to this effect?<\/span><\/p>\n<p><span aria-haspopup=\"dialog\" aria-expanded=\"false\" aria-controls=\"radix-_r_1p_\" data-state=\"closed\">However, there is a catch here, a standard table expression is merely a means of generating a temporary, named result set in your <a href=\"https:\/\/www.wikitechy.com\/tutorials\/sql\/what-is-sql\" target=\"_blank\" rel=\"noopener\">SQL query<\/a>.<\/span> <span aria-haspopup=\"dialog\" aria-expanded=\"false\" aria-controls=\"radix-_r_1q_\" data-state=\"closed\">Imagine it was a little virtual table like when you need to run a query.<\/span><\/p>\n<p>The official-looking definition is as follows:<\/p>\n<p>\ud83d\udc49 A <strong data-start=\"1425\" data-end=\"1458\">common table expression (CTE)<\/strong> in SQL is a temporary result set defined within the execution scope of a single <code class=\"\" data-line=\"\">SELECT<\/code>, <code class=\"\" data-line=\"\">INSERT<\/code>, <code class=\"\" data-line=\"\">UPDATE<\/code>, or <code class=\"\" data-line=\"\">DELETE<\/code> statement.<\/p>\n<p data-start=\"1595\" data-end=\"1622\">And here\u2019s my definition:<\/p>\n<p data-start=\"1624\" data-end=\"1723\">\ud83d\udc49 <em data-start=\"1627\" data-end=\"1721\">It\u2019s like creating a shortcut in SQL so you don\u2019t have to repeat messy code again and again.<\/em><\/p>\n<p data-start=\"1624\" data-end=\"1723\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-16064 \" src=\"https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/09\/cte.webp\" alt=\"\" width=\"612\" height=\"332\" srcset=\"https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/09\/cte.webp 1128w, https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/09\/cte-300x163.webp 300w, https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/09\/cte-1024x556.webp 1024w, https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/09\/cte-768x417.webp 768w, https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/09\/cte-380x206.webp 380w, https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/09\/cte-800x434.webp 800w\" sizes=\"auto, (max-width: 612px) 100vw, 612px\" \/><\/p>\n<h2 data-start=\"1624\" data-end=\"1723\"><strong>The story of why I fell in love with common table expressions<\/strong><\/h2>\n<p data-start=\"1811\" data-end=\"2045\">I\u2019ll be honest: when I first wrote long queries with subqueries inside subqueries, my brain fried. Debugging was a nightmare. Ever opened a query with 200+ lines and no formatting? Yeah\u2026 feels like reading someone\u2019s bad handwriting.<\/p>\n<p data-start=\"2047\" data-end=\"2155\">That\u2019s when I found common table expressions. They gave my queries structure, readability, and sanity.<\/p>\n<p data-start=\"2157\" data-end=\"2202\">Here\u2019s why I think <strong data-start=\"2176\" data-end=\"2199\">CTEs are lifesavers<\/strong>:<\/p>\n<ul data-start=\"2204\" data-end=\"2560\">\n<li data-start=\"2204\" data-end=\"2289\">\n<p data-start=\"2206\" data-end=\"2289\"><strong data-start=\"2206\" data-end=\"2222\">Readable SQL<\/strong> \u2192 Queries feel like they\u2019re telling a story instead of a puzzle.<\/p>\n<\/li>\n<li data-start=\"2290\" data-end=\"2380\">\n<p data-start=\"2292\" data-end=\"2380\"><strong data-start=\"2292\" data-end=\"2310\">Reusable logic<\/strong> \u2192 Instead of repeating the same subquery 5 times, I define it once.<\/p>\n<\/li>\n<li data-start=\"2381\" data-end=\"2458\">\n<p data-start=\"2383\" data-end=\"2458\"><strong data-start=\"2383\" data-end=\"2401\">Debug-friendly<\/strong> \u2192 I can check each step by running the CTE separately.<\/p>\n<\/li>\n<li data-start=\"2459\" data-end=\"2560\">\n<p data-start=\"2461\" data-end=\"2560\"><strong data-start=\"2461\" data-end=\"2482\">Recursive queries<\/strong> \u2192 Perfect for handling hierarchical data (like org charts or family trees).<\/p>\n<\/li>\n<\/ul>\n<p data-start=\"2562\" data-end=\"2664\">If you\u2019ve ever cursed at your SQL for being ugly (I know I have), CTEs are your new best friend.<\/p>\n<p data-start=\"2562\" data-end=\"2664\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-16066 \" src=\"https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/09\/SQL-with-co-to-CTE.webp\" alt=\"\" width=\"577\" height=\"302\" srcset=\"https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/09\/SQL-with-co-to-CTE.webp 1024w, https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/09\/SQL-with-co-to-CTE-300x157.webp 300w, https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/09\/SQL-with-co-to-CTE-768x402.webp 768w, https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/09\/SQL-with-co-to-CTE-380x199.webp 380w, https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/09\/SQL-with-co-to-CTE-800x419.webp 800w\" sizes=\"auto, (max-width: 577px) 100vw, 577px\" \/><\/p>\n<h2 data-start=\"2562\" data-end=\"2664\"><strong>Example of a Common Table Expression in SQL \ud83c\udfaf<\/strong><\/h2>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"sql\">WITH EmployeeCTE AS (\r\n    SELECT EmployeeID, FirstName, LastName, ManagerID\r\n    FROM Employees\r\n)\r\nSELECT * \r\nFROM EmployeeCTE\r\nWHERE ManagerID IS NOT NULL;\r\n<\/pre>\n<p>Notice that magical word <strong data-start=\"2946\" data-end=\"2954\">WITH<\/strong>? That\u2019s the start of a <strong data-start=\"2978\" data-end=\"3005\">common table expression<\/strong>. I named mine <code class=\"\" data-line=\"\">EmployeeCTE<\/code>. Now, I can use it in my main query like a regular table.<\/p>\n<h2><strong>Recursive Common Table Expression (Real-Life) Example<\/strong><\/h2>\n<div class=\"whitespace-pre-line p-2 sm:p-1 min-h-[80px]  max-w-full overflow-x-auto\"><span aria-haspopup=\"dialog\" aria-expanded=\"false\" aria-controls=\"radix-_r_2f_\" data-state=\"closed\">On one occasion, I was asked to determine how the students of one giant organization are reported to another.<\/span> Without CTEs, it was chaos. <span aria-haspopup=\"dialog\" aria-expanded=\"false\" aria-controls=\"radix-_r_2g_\" data-state=\"closed\">It was smooth with recursive common table expression.<\/span><\/div>\n<div><\/div>\n<div>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"sql\">WITH EmployeeHierarchy AS (\r\n    SELECT EmployeeID, ManagerID, 0 AS Level\r\n    FROM Employees\r\n    WHERE ManagerID IS NULL\r\n\r\n    UNION ALL\r\n\r\n    SELECT e.EmployeeID, e.ManagerID, eh.Level + 1\r\n    FROM Employees e\r\n    INNER JOIN EmployeeHierarchy eh\r\n    ON e.ManagerID = eh.EmployeeID\r\n)\r\nSELECT * FROM EmployeeHierarchy;\r\n<\/pre>\n<p data-start=\"3711\" data-end=\"3802\">This beauty pulls out the entire org chart\u2014bosses, managers, juniors\u2014all in one query. \ud83d\ude80<\/p>\n<p data-start=\"3804\" data-end=\"3855\">That\u2019s the magic of <strong data-start=\"3824\" data-end=\"3852\">common table expressions<\/strong>.<\/p>\n<p data-start=\"3804\" data-end=\"3855\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-16067 \" src=\"https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/09\/cte_in-sql.webp\" alt=\"\" width=\"640\" height=\"360\" srcset=\"https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/09\/cte_in-sql.webp 800w, https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/09\/cte_in-sql-300x169.webp 300w, https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/09\/cte_in-sql-768x432.webp 768w, https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/09\/cte_in-sql-380x214.webp 380w\" sizes=\"auto, (max-width: 640px) 100vw, 640px\" \/><\/p>\n<h2 data-start=\"3804\" data-end=\"3855\"><strong>CTE vs Subquery vs Temp Table \u26a1<\/strong><\/h2>\n<p>Well, you may say: Why not simply use subqueries or temp table instead of common table expressions?<\/p>\n<p>Here\u2019s my honest take:<\/p>\n<ul>\n<li><span aria-haspopup=\"dialog\" aria-expanded=\"false\" aria-controls=\"radix-_r_2o_\" data-state=\"closed\">Subqueries &#8211; good with little stuff but terrible when nested.<\/span><\/li>\n<li>Temp Tables-Temporary tables are used to hold intermediate results used in more than one query.<\/li>\n<li><span aria-haspopup=\"dialog\" aria-expanded=\"false\" aria-controls=\"radix-_r_2q_\" data-state=\"closed\">Common Table Expression Perfect middle ground.<\/span> <span aria-haspopup=\"dialog\" aria-expanded=\"false\" aria-controls=\"radix-_r_2r_\" data-state=\"closed\">Less complex than subqueries, less complex than temp tables.<\/span><\/li>\n<\/ul>\n<p>If I had to explain with food \ud83c\udf54:<\/p>\n<ul>\n<li>Subqueries = fast food (hurried and messy).<\/li>\n<li><span aria-haspopup=\"dialog\" aria-expanded=\"false\" aria-controls=\"radix-_r_2t_\" data-state=\"closed\">Temp tables = preparing a large meal (takes time, but can be used again).<\/span><\/li>\n<li>CTEs = a healthy snack (clean, fast, balanced).<\/li>\n<\/ul>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-16068 \" src=\"https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/09\/CTE-vs-Subquery-vs-Temp-Table.webp\" alt=\"\" width=\"587\" height=\"391\" srcset=\"https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/09\/CTE-vs-Subquery-vs-Temp-Table.webp 1536w, https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/09\/CTE-vs-Subquery-vs-Temp-Table-300x200.webp 300w, https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/09\/CTE-vs-Subquery-vs-Temp-Table-1024x683.webp 1024w, https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/09\/CTE-vs-Subquery-vs-Temp-Table-768x512.webp 768w, https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/09\/CTE-vs-Subquery-vs-Temp-Table-380x253.webp 380w, https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/09\/CTE-vs-Subquery-vs-Temp-Table-800x533.webp 800w, https:\/\/www.kaashivinfotech.com\/blog\/wp-content\/uploads\/2025\/09\/CTE-vs-Subquery-vs-Temp-Table-1160x773.webp 1160w\" sizes=\"auto, (max-width: 587px) 100vw, 587px\" \/><\/p>\n<h2 data-start=\"5095\" data-end=\"5149\">Where I Use Common Table Expressions in Real Life<\/h2>\n<p data-start=\"5151\" data-end=\"5203\">Here are places where <strong data-start=\"5173\" data-end=\"5200\">CTEs save me every week<\/strong>:<\/p>\n<ul data-start=\"5205\" data-end=\"5477\">\n<li data-start=\"5205\" data-end=\"5264\">\n<p data-start=\"5207\" data-end=\"5264\"><strong data-start=\"5207\" data-end=\"5224\">Data Cleaning<\/strong> \u2192 Break down messy data step by step.<\/p>\n<\/li>\n<li data-start=\"5265\" data-end=\"5354\">\n<p data-start=\"5267\" data-end=\"5354\"><strong data-start=\"5267\" data-end=\"5280\">Analytics<\/strong> \u2192 Create layered aggregations (sales by month, by region, by category).<\/p>\n<\/li>\n<li data-start=\"5355\" data-end=\"5404\">\n<p data-start=\"5357\" data-end=\"5404\"><strong data-start=\"5357\" data-end=\"5370\">Reporting<\/strong> \u2192 Easier to read for teammates.<\/p>\n<\/li>\n<li data-start=\"5405\" data-end=\"5477\">\n<p data-start=\"5407\" data-end=\"5477\"><strong data-start=\"5407\" data-end=\"5428\">Recursive queries<\/strong> \u2192 Org charts, folder structures, family trees.<\/p>\n<\/li>\n<\/ul>\n<p data-start=\"5479\" data-end=\"5625\">If you\u2019re a data analyst, BI developer, or even a student writing SQL for assignments, common table expressions will feel like a cheat code.<\/p>\n<h2 data-start=\"5632\" data-end=\"5702\">How to Write Your First Common Table Expression (Step-by-Step)<\/h2>\n<ol data-start=\"5704\" data-end=\"5863\">\n<li data-start=\"5704\" data-end=\"5740\">\n<p data-start=\"5707\" data-end=\"5740\">Start your query with <strong data-start=\"5729\" data-end=\"5737\">WITH<\/strong>.<\/p>\n<\/li>\n<li data-start=\"5741\" data-end=\"5783\">\n<p data-start=\"5744\" data-end=\"5783\">Name your <strong data-start=\"5754\" data-end=\"5761\">CTE<\/strong> (e.g., <code class=\"\" data-line=\"\">SalesCTE<\/code>).<\/p>\n<\/li>\n<li data-start=\"5784\" data-end=\"5825\">\n<p data-start=\"5787\" data-end=\"5825\">Write a subquery inside parentheses.<\/p>\n<\/li>\n<li data-start=\"5826\" data-end=\"5863\">\n<p data-start=\"5829\" data-end=\"5863\">Call the CTE in your main query.<\/p>\n<\/li>\n<\/ol>\n<p data-start=\"5865\" data-end=\"5875\">Example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"sql\">WITH SalesCTE AS (\r\n    SELECT CustomerID, SUM(Amount) AS TotalSales\r\n    FROM Sales\r\n    GROUP BY CustomerID\r\n)\r\nSELECT * \r\nFROM SalesCTE\r\nWHERE TotalSales &gt; 1000;\r\n<\/pre>\n<p>That\u2019s it. Simple. You just wrote your first common table expression.<\/p>\n<h2><strong>Final Thoughts<\/strong><\/h2>\n<p><span aria-haspopup=\"dialog\" aria-expanded=\"false\" aria-controls=\"radix-_r_31_\" data-state=\"closed\">The initial usage of a common table expression made me feel that I had discovered a secret superpower in the SQL.<\/span> <span aria-haspopup=\"dialog\" aria-expanded=\"false\" aria-controls=\"radix-_r_32_\" data-state=\"closed\">There is no longer any ugly nested subqueries.<\/span> <span aria-haspopup=\"dialog\" aria-expanded=\"false\" aria-controls=\"radix-_r_33_\" data-state=\"closed\">Enough with incomprehensible questions that caused my teammates to weep.<\/span><\/p>\n<p>If You Want to learn <a href=\"https:\/\/www.kaashivinfotech.com\/sql-server-course-in-chennai\/\">Sql Course<\/a>, or <a href=\"https:\/\/internship.kaashivinfotech.com\/sql-internship\/\">SQL Internship<\/a> Visit Our Website <a href=\"https:\/\/www.kaashivinfotech.com\/\">www.kaashivinfotech.com<\/a>.<\/p>\n<p><span aria-haspopup=\"dialog\" aria-expanded=\"false\" aria-controls=\"radix-_r_34_\" data-state=\"closed\">In case you are new, get used to writing small queries using CTEs.<\/span> <span aria-haspopup=\"dialog\" aria-expanded=\"false\" aria-controls=\"radix-_r_35_\" data-state=\"closed\">In the long run, you will discover that they not only tidy up your SQL, but also improve its readability by other people.<\/span><\/p>\n<p><span aria-haspopup=\"dialog\" aria-expanded=\"false\" aria-controls=\"radix-_r_36_\" data-state=\"closed\">And by the way, when you get in a jam, you should not panic.<\/span> We\u2019ve all been there. <span aria-haspopup=\"dialog\" aria-expanded=\"false\" aria-controls=\"radix-_r_37_\" data-state=\"closed\">Take a simple case, and deconstruct it, and reattempt it.<\/span> You\u2019ll thank yourself later.<\/p>\n<h2>Related Reads:<\/h2>\n<ul>\n<li>\n<p class=\"entry-title\"><a href=\"https:\/\/www.kaashivinfotech.com\/blog\/sql-update-query-explained-2025-guide\/\">SQL UPDATE Query Explained (2025 Guide): Syntax, Examples, and Mistakes Developers Still Make<\/a><\/p>\n<\/li>\n<li>\n<p class=\"entry-title\"><a href=\"https:\/\/www.kaashivinfotech.com\/blog\/normalization-in-dbms-1nf-2nf-3nf\/\">What is Normalization in DBMS \u2013 1NF, 2NF, 3NF Explained with Examples (2025 Guide)<\/a><\/p>\n<\/li>\n<\/ul>\n<p data-start=\"5479\" data-end=\"5625\">\n<\/div>\n","protected":false},"excerpt":{"rendered":"What is a Common Table Expression (CTE) in SQL? Let\u2019s keep it real. When I first encountered the&hellip;","protected":false},"author":8,"featured_media":16065,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"csco_singular_sidebar":"default","csco_page_header_type":"default","csco_page_load_nextpost":"default","footnotes":""},"categories":[3204],"tags":[9286,9289,9292,9290,9291,9287,9293,9288],"class_list":["post-16062","post","type-post","status-publish","format-standard","has-post-thumbnail","category-sql","tag-common-table-expression-example","tag-common-table-expression-in-sql-server","tag-common-table-expression-mysql","tag-common-table-expression-oracle","tag-common-table-expression-postgres","tag-common-table-expression-sql","tag-common-table-expression-vs-subquery","tag-common-table-expression-w3schools","cs-entry"],"_links":{"self":[{"href":"https:\/\/www.kaashivinfotech.com\/blog\/wp-json\/wp\/v2\/posts\/16062","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.kaashivinfotech.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.kaashivinfotech.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.kaashivinfotech.com\/blog\/wp-json\/wp\/v2\/users\/8"}],"replies":[{"embeddable":true,"href":"https:\/\/www.kaashivinfotech.com\/blog\/wp-json\/wp\/v2\/comments?post=16062"}],"version-history":[{"count":1,"href":"https:\/\/www.kaashivinfotech.com\/blog\/wp-json\/wp\/v2\/posts\/16062\/revisions"}],"predecessor-version":[{"id":16069,"href":"https:\/\/www.kaashivinfotech.com\/blog\/wp-json\/wp\/v2\/posts\/16062\/revisions\/16069"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.kaashivinfotech.com\/blog\/wp-json\/wp\/v2\/media\/16065"}],"wp:attachment":[{"href":"https:\/\/www.kaashivinfotech.com\/blog\/wp-json\/wp\/v2\/media?parent=16062"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.kaashivinfotech.com\/blog\/wp-json\/wp\/v2\/categories?post=16062"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.kaashivinfotech.com\/blog\/wp-json\/wp\/v2\/tags?post=16062"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}