Why Use A CTE?: Common Table Expression (CTE)
Why Use A CTE?: Common Table Expression (CTE)
CTE
A Common Table Expression (CTE) in SQL is like a temporary, reusable table that
you create within a query. You can use it to make your query easier to read and
manage, especially when dealing with complex queries or subqueries.
CTEs are declared using the WITH keyword and exist only for the duration of the
query they are part of.
• Reusable: The same CTE can be referenced multiple times in the main query.
Syntax of a CTE
WITH cte_name AS ( -- Your CTE query here SELECT column1, column2 FROM ta
ble_name WHERE condition ) -- Main query that uses the CTE SELECT * FROM
cte_name;
https://sponge-tick-989.notion.site/CTE-144619fbb33d80d8a5d5cbb10c5605c0 1/3
11/24/24, 10:24 PM CTE
Question 1:
Find the average salary of each department using a CTE.
Question 2:
List employees earning above their department’s average salary.
Question 3:
Find the most recently joined employee in each department.
https://sponge-tick-989.notion.site/CTE-144619fbb33d80d8a5d5cbb10c5605c0 2/3
11/24/24, 10:24 PM CTE
Question 4:
Find the total salary paid in departments where the average salary is above 60,000
https://sponge-tick-989.notion.site/CTE-144619fbb33d80d8a5d5cbb10c5605c0 3/3