A Comprehensive Resource for Microsoft Technologies

Welcome, your go-to destination for everything related to .NET and Microsoft technologies. With over 10 years of experience in the IT industry, I am excited to share my knowledge and insights on this platform. This blog is dedicated to providing valuable information, tips, and tutorials that are not only relevant to the rapidly evolving IT industry but also essential for individuals working on real-time projects and preparing for interviews

8.1 Common Table Expressions (CTEs)

 Common Table Expressions (CTEs) are temporary result sets that can be referenced within a SELECT, INSERT, UPDATE, or DELETE statement. They provide a way to break down complex queries into simpler, more manageable components.

1. Introduction to CTEs

A CTE is defined using the WITH clause and can be referenced within the same query. It improves readability and makes complex queries easier to understand.

2. Creating a Simple CTE

Let's start by creating a simple CTE that selects data from a table:

WITH SampleCTE AS (
    SELECT
        EmployeeID,
        FirstName,
        LastName
    FROM
        Employees
)
SELECT *
FROM SampleCTE;

Output:

EmployeeIDFirstNameLastName
1JohnDoe
2JaneSmith
3BobJohnson

3. CTEs with Joins

You can use CTEs in combination with JOIN operations to create more complex queries:

WITH EmployeeCTE AS (
    SELECT
        EmployeeID,
        FirstName,
        LastName
    FROM
        Employees
),
DepartmentCTE AS (
    SELECT
        DepartmentID,
        DepartmentName
    FROM
        Departments
)
SELECT
    e.EmployeeID,
    e.FirstName,
    e.LastName,
    d.DepartmentName
FROM
    EmployeeCTE e
JOIN DepartmentCTE d ON e.EmployeeID = d.DepartmentID;

Output:

EmployeeIDFirstNameLastNameDepartmentName
1JohnDoeSales
2JaneSmithMarketing
3BobJohnsonFinance

4. Recursive CTEs

Recursive CTEs can be used to work with hierarchical data, such as organizational charts:

WITH EmployeeHierarchy AS (
    SELECT
        EmployeeID,
        ManagerID,
        FirstName,
        LastName,
        0 AS Level
    FROM
        Employees
    WHERE
        ManagerID IS NULL
    UNION ALL
    SELECT
        e.EmployeeID,
        e.ManagerID,
        e.FirstName,
        e.LastName,
        eh.Level + 1
    FROM
        Employees e
    JOIN EmployeeHierarchy eh ON e.ManagerID = eh.EmployeeID
)
SELECT
    EmployeeID,
    FirstName,
    LastName,
    Level
FROM
    EmployeeHierarchy;

Output:

EmployeeIDFirstNameLastNameLevel
1JohnDoe0
2JaneSmith1
3BobJohnson2

This tutorial provides a basic understanding of Common Table Expressions and demonstrates their usage in different scenarios. Feel free to explore further and apply CTEs to your specific use cases.