Articles → SQL SERVER → Common Table Expression (CTE) In SQL Server

Common Table Expression (CTE) In SQL Server






Purpose





Syntax


WITH <CTE_Name> AS (
<Select query>
)



Example




Picture showing the data in the Product table
Click to Enlarge



Picture showing the data in the Orders table
Click to Enlarge



;WITH sales AS (
    SELECT product_id, SUM(quantity * price) AS revenue
    FROM orders
    GROUP BY product_id
)
SELECT product_id, revenue
FROM sales
WHERE revenue > 20;



Output


Picture showing the output of the Common Table Expression in SQL server
Click to Enlarge




Posted By  -  Karan Gupta
 
Posted On  -  Friday, April 7, 2023

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250