Paramclasses Academy - Blog

Tutorials Details

←
Post 20 of 40
→

SQL Subqueries and Common Table Expressions (CTEs) in SQL Server: Complete Beginner's Guide with Examples

SQL Subqueries and Common Table Expressions (CTEs) in SQL Server: Complete Beginner's Guide with Examples

November 17, 2026

SQL Subqueries and Common Table Expressions (CTEs) in SQL Server: Complete Beginner's Guide with Examples

Introduction

When working with Microsoft SQL Server, developers often need to write queries that perform multiple operations, retrieve data based on another query, or simplify complex database calculations.

For example, imagine that you are developing an Employee Management System. You want to find employees whose salary is greater than the company's average salary. You may first need to calculate the average salary and then retrieve employees based on that result.

SQL Server provides two powerful techniques to handle such requirements:

  • Subqueries – Queries written inside another SQL query.

  • Common Table Expressions (CTEs) – Named temporary result sets that make complex queries easier to read and manage.

In this tutorial by Param Classes, we will learn what subqueries and CTEs are, understand their syntax, explore different types, and practise them with real-world SQL Server examples.

1. What Is a Subquery in SQL Server?

A Subquery is a SQL query written inside another SQL query.

The inner query executes as part of the outer query and provides a result that the outer query can use.

Subqueries are commonly used with:

  • SELECT statements.

  • INSERT statements.

  • UPDATE statements.

  • DELETE statements.

  • WHERE clauses.

  • HAVING clauses.

  • FROM clauses.

Basic Syntax

SELECT column_name
FROM table_name
WHERE column_name =
(
    SELECT column_name
    FROM another_table
);

Explanation:

  • The inner SELECT statement is called the subquery.

  • The outer SELECT statement is called the main query.

  • The result of the inner query is used by the outer query.

Simple Example

Suppose you have an Employees table and want to find employees earning more than a particular salary.

SELECT *
FROM Employees
WHERE Salary >
(
    SELECT 35000
);

This query returns employees whose salary is greater than 35000.

Important: A subquery is not always required to be written in parentheses only for equality comparisons. Its structure and placement depend on the SQL operation being performed.

2. Create Sample Database Tables

Before practising subqueries and CTEs, let's create sample tables.

We will use two tables:

  1. Employees

  2. Departments

Step 1: Create the Departments Table

CREATE TABLE Departments
(
    DepartmentID INT PRIMARY KEY,
    DepartmentName VARCHAR(50)
);

Step 2: Insert Department Records

INSERT INTO Departments
(DepartmentID, DepartmentName)
VALUES
(1, 'IT'),
(2, 'HR'),
(3, 'Sales'),
(4, 'Finance');

Step 3: Create the Employees Table

CREATE TABLE Employees
(
    EmployeeID INT PRIMARY KEY,
    EmployeeName VARCHAR(50),
    DepartmentID INT,
    Salary DECIMAL(10,2)
);

Step 4: Insert Employee Records

INSERT INTO Employees
(EmployeeID, EmployeeName, DepartmentID, Salary)
VALUES
(1, 'Rahul', 1, 40000),
(2, 'Priya', 2, 35000),
(3, 'Amit', 1, 45000),
(4, 'Neha', 2, 30000),
(5, 'Rohit', 3, 38000),
(6, 'Anjali', 1, 50000),
(7, 'Karan', 3, 42000),
(8, 'Pooja', 4, 36000);

Step 5: Display Employee Records

SELECT *
FROM Employees;

Employees Table

EmployeeID EmployeeName DepartmentID Salary
1 Rahul 1 40000
2 Priya 2 35000
3 Amit 1 45000
4 Neha 2 30000
5 Rohit 3 38000
6 Anjali 1 50000
7 Karan 3 42000
8 Pooja 4 36000

Departments Table

DepartmentID DepartmentName
1 IT
2 HR
3 Sales
4 Finance

These tables will help us understand subqueries and CTEs through practical examples.

3. Types of Subqueries in SQL Server

Subqueries can be classified according to the type of result they return and how they interact with the outer query.

Important types include:

  1. Single-Row Subquery

  2. Multiple-Row Subquery

  3. Multiple-Column Subquery

  4. Correlated Subquery

  5. Nested Subquery

Let's understand each type.

4. Single-Row Subquery

A Single-Row Subquery returns a single row of data.

It is commonly used with comparison operators such as:

  • =

  •  

     

  • <

  •  

    =

  • <=

  • <>

Example: Find Employees Earning More Than Average Salary

SELECT *
FROM Employees
WHERE Salary >
(
    SELECT AVG(Salary)
    FROM Employees
);

Expected Output

EmployeeID EmployeeName DepartmentID Salary
3 Amit 1 45000
6 Anjali 1 50000
7 Karan 3 42000

Explanation:

  1. The inner query calculates the average employee salary.

  2. The outer query compares each employee's salary with that average.

  3. Only employees earning more than the average salary are returned.

The average salary in this example is 39500.

Result: The query identifies employees whose salary is greater than 39500.

5. Multiple-Row Subquery

A Multiple-Row Subquery returns more than one row.

Operators such as IN, ANY, and ALL can be used with multiple-row subqueries.

Example 1: IN Operator with Subquery

Suppose you want to find employees working in departments where the department ID is 1 or 3.

SELECT *
FROM Employees
WHERE DepartmentID IN
(
    SELECT DepartmentID
    FROM Departments
    WHERE DepartmentName IN ('IT', 'Sales')
);

Expected Output

EmployeeName DepartmentID Salary
Rahul 1 40000
Amit 1 45000
Rohit 3 38000
Anjali 1 50000
Karan 3 42000

Explanation:

  • The inner query retrieves department IDs for IT and Sales.

  • The outer query selects employees whose DepartmentID matches those values.

  • IN checks whether a value exists in the returned list.

Example 2: ANY Operator with Subquery

The ANY operator returns rows when a comparison is true for at least one value returned by the subquery.

SELECT *
FROM Employees
WHERE Salary > ANY
(
    SELECT Salary
    FROM Employees
    WHERE DepartmentID = 2
);

Explanation:

The HR department has salaries of 35000 and 30000.

The query returns employees whose salary is greater than at least one of these values.

Example 3: ALL Operator with Subquery

The ALL operator returns rows when a comparison is true for every value returned by the subquery.

SELECT *
FROM Employees
WHERE Salary > ALL
(
    SELECT Salary
    FROM Employees
    WHERE DepartmentID = 2
);

Explanation:

The query returns employees whose salary is greater than every salary in the HR department.

Important: ANY and ALL can be useful when comparing a value against a set of values returned by another query.

6. Multiple-Column Subquery

A Multiple-Column Subquery returns more than one column from the inner query.

SQL Server supports comparing multiple columns using appropriate row-value alternatives, such as EXISTS with matching conditions.

Example: Find Employees Matching a Department and Salary Combination

SELECT *
FROM Employees E
WHERE EXISTS
(
    SELECT 1
    FROM Employees E2
    WHERE E2.DepartmentID = E.DepartmentID
      AND E2.Salary = E.Salary
);

Explanation:

  • The inner query checks whether a matching department and salary combination exists.

  • EXISTS returns TRUE when the inner query finds at least one matching row.

  • The outer query returns employees satisfying that condition.

This example demonstrates matching multiple columns through a correlated EXISTS condition.

7. Correlated Subquery in SQL Server

A Correlated Subquery is a subquery that references a column from the outer query.

Unlike a simple independent subquery, a correlated subquery depends on the current row being processed by the outer query.

Example: Find Employees Earning More Than Their Department's Average Salary

SELECT
    E.EmployeeID,
    E.EmployeeName,
    E.DepartmentID,
    E.Salary
FROM Employees E
WHERE E.Salary >
(
    SELECT AVG(E2.Salary)
    FROM Employees E2
    WHERE E2.DepartmentID = E.DepartmentID
);

Expected Output

EmployeeName DepartmentID Salary
Amit 1 45000
Anjali 1 50000
Priya 2 35000
Karan 3 42000

Explanation:

  1. The outer query processes employee records.

  2. The inner query calculates the average salary for the current employee's department.

  3. The outer query compares the employee's salary with that department's average.

  4. Employees earning more than their department average are displayed.

Real-world use: Correlated subqueries are useful when comparing each record with a value calculated from its related group.

8. Nested Subquery in SQL Server

A Nested Subquery means writing one subquery inside another subquery.

It is useful when information must be retrieved through multiple levels of conditions.

Example: Find Employees Working in the Department with the Highest Average Salary

SELECT *
FROM Employees
WHERE DepartmentID =
(
    SELECT DepartmentID
    FROM Employees
    GROUP BY DepartmentID
    HAVING AVG(Salary) =
    (
        SELECT MAX(DepartmentAverage)
        FROM
        (
            SELECT AVG(Salary) AS DepartmentAverage
            FROM Employees
            GROUP BY DepartmentID
        ) AS DepartmentSummary
    )
);

Explanation:

  1. The innermost query calculates average salary for each department.

  2. The next query finds the highest department average.

  3. The middle query identifies the department having that average.

  4. The outer query retrieves employees from that department.

Result: The query identifies employees belonging to the department with the highest average salary.

9. What Is EXISTS in SQL Server?

The EXISTS operator checks whether a subquery returns at least one row.

It returns TRUE when matching records exist and FALSE when no matching records exist.

Syntax

SELECT column_name
FROM table_name
WHERE EXISTS
(
    SELECT 1
    FROM another_table
    WHERE condition
);

Example: Find Departments Having Employees

SELECT *
FROM Departments D
WHERE EXISTS
(
    SELECT 1
    FROM Employees E
    WHERE E.DepartmentID = D.DepartmentID
);

Expected Output

DepartmentID DepartmentName
1 IT
2 HR
3 Sales
4 Finance

Explanation:

The query checks whether each department has at least one employee.

NOT EXISTS Example

If you want to find departments that do not have any employees, use NOT EXISTS.

SELECT *
FROM Departments D
WHERE NOT EXISTS
(
    SELECT 1
    FROM Employees E
    WHERE E.DepartmentID = D.DepartmentID
);

If a department has no matching employee, it will appear in the result.

10. What Is a Common Table Expression (CTE)?

A Common Table Expression (CTE) is a named temporary result set defined within the execution scope of a single SQL statement.

CTEs help developers organize complex SQL queries into smaller, understandable parts.

They are commonly used for:

  • Simplifying complex queries.

  • Organizing multiple query steps.

  • Working with grouped data.

  • Writing recursive queries.

  • Improving query readability.

Basic Syntax

WITH CTE_Name AS
(
    SELECT column_name
    FROM table_name
    WHERE condition
)
SELECT *
FROM CTE_Name;

Explanation:

  • WITH starts the CTE definition.

  • CTE_Name is the name assigned to the result set.

  • The query inside parentheses defines the CTE.

  • The outer query uses the CTE by its name.

Important: A CTE is not a permanent database table. Its scope is limited to the single statement immediately following its definition.

11. Create Your First CTE in SQL Server

Let's create a simple CTE that retrieves employees earning more than 35000.

Example

WITH HighSalaryEmployees AS
(
    SELECT *
    FROM Employees
    WHERE Salary > 35000
)
SELECT *
FROM HighSalaryEmployees;

Expected Output

EmployeeName DepartmentID Salary
Rahul 1 40000
Amit 1 45000
Rohit 3 38000
Anjali 1 50000
Karan 3 42000
Pooja 4 36000

Explanation:

  1. The CTE named HighSalaryEmployees is created.

  2. The inner query selects employees whose salary is greater than 35000.

  3. The outer SELECT retrieves records from the CTE.

This makes the query easier to read and maintain.

12. CTE with Multiple Columns

A CTE can return multiple columns from a table.

Example: Display Employee Names and Salaries

WITH EmployeeDetails AS
(
    SELECT
        EmployeeID,
        EmployeeName,
        Salary
    FROM Employees
)
SELECT *
FROM EmployeeDetails;

Explanation:

The EmployeeDetails CTE stores the result of the SELECT query for use by the immediately following statement.

You can also give explicit column names to a CTE.

WITH EmployeeDetails
(
    ID,
    Name,
    MonthlySalary
)
AS
(
    SELECT
        EmployeeID,
        EmployeeName,
        Salary
    FROM Employees
)
SELECT *
FROM EmployeeDetails;

13. CTE with GROUP BY and Aggregate Functions

CTEs can be combined with GROUP BY and aggregate functions to prepare reports.

Example: Department-Wise Salary Report

WITH DepartmentSalary AS
(
    SELECT
        DepartmentID,
        COUNT(*) AS TotalEmployees,
        SUM(Salary) AS TotalSalary,
        AVG(Salary) AS AverageSalary
    FROM Employees
    GROUP BY DepartmentID
)
SELECT *
FROM DepartmentSalary;

Expected Output

DepartmentID TotalEmployees TotalSalary AverageSalary
1 3 135000 45000
2 2 65000 32500
3 2 80000 40000
4 1 36000 36000

Explanation:

  • GROUP BY creates department-wise groups.

  • COUNT() counts employees in each department.

  • SUM() calculates total salary.

  • AVG() calculates average salary.

  • The outer query displays the CTE results.

14. Multiple CTEs in a Single SQL Query

SQL Server allows you to define multiple CTEs in one WITH clause by separating their definitions with commas.

Example: Employee and Department Salary Summary

WITH EmployeeCount AS
(
    SELECT
        DepartmentID,
        COUNT(*) AS TotalEmployees
    FROM Employees
    GROUP BY DepartmentID
),
SalarySummary AS
(
    SELECT
        DepartmentID,
        SUM(Salary) AS TotalSalary,
        AVG(Salary) AS AverageSalary
    FROM Employees
    GROUP BY DepartmentID
)
SELECT
    EC.DepartmentID,
    EC.TotalEmployees,
    SS.TotalSalary,
    SS.AverageSalary
FROM EmployeeCount EC
INNER JOIN SalarySummary SS
    ON EC.DepartmentID = SS.DepartmentID;

Explanation:

  1. EmployeeCount calculates the number of employees in each department.

  2. SalarySummary calculates total and average salary.

  3. The final SELECT combines both CTE results.

  4. INNER JOIN matches the records using DepartmentID.

Result: Multiple CTEs help divide a complex query into logical steps.

15. Recursive CTE in SQL Server

A Recursive CTE is a CTE that references itself.

It is useful when working with hierarchical data, such as:

  • Employee-manager relationships.

  • Organization structures.

  • Category and subcategory relationships.

  • Parent-child records.

  • Hierarchical product structures.

A recursive CTE generally contains two parts:

  1. Anchor Member: The initial query that provides the starting result.

  2. Recursive Member: The query that references the CTE and generates the next level.

Example: Generate Numbers from 1 to 5

WITH NumberSeries AS
(
    SELECT 1 AS Number

    UNION ALL

    SELECT Number + 1
    FROM NumberSeries
    WHERE Number < 5
)
SELECT *
FROM NumberSeries
OPTION (MAXRECURSION 10);

Expected Output

Number
1
2
3
4
5

Explanation:

  1. The anchor member starts with number 1.

  2. The recursive member adds 1 to the previous number.

  3. The condition Number < 5 controls the recursion.

  4. Recursion stops when the condition is no longer true.

Important: SQL Server provides a default recursion limit for recursive CTEs. MAXRECURSION can be used to control the permitted recursion depth.

16. Difference Between Subquery and CTE

Both subqueries and CTEs help solve complex SQL problems, but they have different structures and usage patterns.

Feature Subquery CTE
Definition Query inside another query Named result set
Readability Can become difficult in complex queries Often easier to organize
Reusability Usually written wherever needed Can be referenced multiple times in the same statement
Recursive Queries Not directly recursive by itself Supports recursive queries
Scope Depends on the query in which it is written One following statement
Best Use Simple nested conditions Organizing complex query logic

Important: A CTE is not automatically faster than a subquery. SQL Server's query optimizer determines the execution plan based on the query and available database information.

17. Subquery vs CTE: Practical Comparison

Suppose you want to find employees earning more than the company's average salary.

Using a Subquery

SELECT *
FROM Employees
WHERE Salary >
(
    SELECT AVG(Salary)
    FROM Employees
);

Using a CTE

WITH AverageSalary AS
(
    SELECT AVG(Salary) AS AvgSalary
    FROM Employees
)
SELECT E.*
FROM Employees E
CROSS JOIN AverageSalary A
WHERE E.Salary > A.AvgSalary;

Explanation:

Both queries calculate the average salary and retrieve employees earning more than that value.

The subquery performs the calculation inside the WHERE clause, while the CTE gives the calculated result a meaningful name.

18. Common Mistakes to Avoid

  1. Using an incorrect comparison operator: A subquery returning multiple rows cannot be used with an ordinary single-value comparison such as =. Consider IN, ANY, ALL, or EXISTS where appropriate.

  2. Forgetting parentheses: A subquery written inside another query must follow the correct SQL syntax.

  3. Using the wrong column in a correlated subquery: Make sure the inner query references the correct outer table alias.

  4. Ignoring NULL values: NULL values can affect comparisons and IN or NOT IN conditions. Consider EXISTS or NOT EXISTS when appropriate.

  5. Forgetting the CTE name: The outer query must refer to the correct CTE name.

  6. Using a CTE across multiple statements: A CTE is available only to the single statement immediately following its definition.

  7. Forgetting the statement terminator before WITH: If another statement precedes a CTE in the same batch, terminate the previous statement with a semicolon.

  8. Creating unnecessary nested queries: Use a simpler query when it can solve the problem clearly.

  9. Misunderstanding recursive CTEs: Always provide a suitable stopping condition to prevent unwanted recursion.

  10. Assuming CTEs always improve performance: Readability and execution performance are different considerations.

19. Practice Questions

Create the Employees and Departments tables and practise the following queries:

  1. Find employees earning more than the average salary using a subquery.

  2. Find employees working in the IT department using IN and a subquery.

  3. Find employees earning more than every employee in the HR department using ALL.

  4. Find employees earning more than at least one employee in the HR department using ANY.

  5. Find departments that have at least one employee using EXISTS.

  6. Find departments that do not have employees using NOT EXISTS.

  7. Find employees earning more than their department's average salary using a correlated subquery.

  8. Find the department having the highest average salary using a nested subquery.

  9. Create a CTE to display employees earning more than 35000.

  10. Create a CTE to calculate department-wise employee counts.

  11. Create multiple CTEs to calculate total and average salary by department.

  12. Create a recursive CTE to generate numbers from 1 to 10.

20. Frequently Asked Questions (FAQs)

Q1. What is a subquery in SQL Server?

A subquery is a SQL query written inside another SQL query. Its result is used by the outer query.

Q2. What are the different types of subqueries?

Common classifications include single-row, multiple-row, multiple-column, correlated, and nested subqueries.

Q3. What is a correlated subquery?

A correlated subquery references a column from the outer query and depends on the current outer row.

Q4. What is the IN operator used for with subqueries?

IN checks whether a value matches any value returned by a subquery.

Q5. What is the difference between ANY and ALL?

ANY requires a comparison to be true for at least one returned value. ALL requires it to be true for every returned value.

Q6. What is EXISTS in SQL Server?

EXISTS checks whether a subquery returns at least one row.

Q7. What is a CTE in SQL Server?

A Common Table Expression is a named temporary result set defined using the WITH clause and available to the immediately following SQL statement.

Q8. What is the main advantage of using CTEs?

CTEs make complex queries easier to read, organize, and maintain.

Q9. What is a recursive CTE?

A recursive CTE is a CTE that references itself to process hierarchical or sequential data.

Q10. Can we use multiple CTEs in one query?

Yes. Multiple CTEs can be defined in a single WITH clause, separated by commas.

Q11. Are CTEs faster than subqueries?

Not necessarily. SQL Server's query optimizer determines the execution strategy. CTEs primarily help organize query logic.

Q12. Can a CTE be used in multiple SQL statements?

A CTE is scoped to the single statement immediately following its definition. For reuse across multiple statements, consider a temporary table or another suitable database object.

21. Conclusion

In this tutorial, we learned two important SQL Server concepts: Subqueries and Common Table Expressions (CTEs).

We explored how subqueries work inside SELECT statements, understood single-row and multiple-row subqueries, and practised IN, ANY, ALL, EXISTS, correlated subqueries, and nested queries.

We also learned how to create CTEs using the WITH clause, work with multiple CTEs, combine CTEs with GROUP BY and aggregate functions, and generate sequential results using recursive CTEs.

Both techniques are important for writing organized, readable, and powerful SQL queries. Subqueries are useful for nested conditions and comparisons, while CTEs help break complex query logic into understandable steps.

At Param Classes, our goal is to help students learn SQL Server through practical examples, structured tutorials, and real-world database concepts. Practise these queries in SQL Server Management Studio (SSMS) to strengthen your database development skills.

Keep learning and improving your SQL Server skills with Param Classes!

←
Post 20 of 40
→