SQL Server continues to be one of the most potent relational database systems in today's data-driven world. However, the ability to write sophisticated SQL queries frequently distinguishes novices from pros. Business reports, analytics dashboards, and performance-driven apps are built on complex queries.
Joins, subqueries, window functions, CTEs, pivoting, and other real-world complex SQL Server queries will all be covered in this article with clear examples.
1. Using Subqueries for Conditional Data Retrieval
Scenario:
You need to find all employees whose salary is higher than the average salary of their department.
Query:
SELECT
EmpName,
DepartmentId,
Salary
FROM Employees E
WHERE Salary > (
SELECT AVG(Salary)
FROM Employees
WHERE DepartmentId = E.DepartmentId
);
Explanation:
- The inner query calculates the average salary per department.
- The outer query compares each employee’s salary to that departmental average.
This is a correlated subquery, as it depends on the outer query.
2. Combining Multiple Tables with JOINS
Scenario:
Retrieve all orders along with customer names and product details.
Query:
SELECT
C.CustomerName,
O.OrderId,
P.ProductName,
O.OrderDate,
OD.Quantity,
(OD.Quantity * OD.UnitPrice) AS TotalAmount
FROM Orders O
INNER JOIN Customers C ON O.CustomerId = C.CustomerId
INNER JOIN OrderDetails OD ON O.OrderId = OD.OrderId
INNER JOIN Products P ON OD.ProductId = P.ProductId
WHERE O.OrderDate >= '2025-01-01'
ORDER BY O.OrderDate DESC;
Explanation:
This query combines four tables using inner joins to give a comprehensive view of orders placed in 2025.
3. Ranking Data Using Window Functions
Scenario:
List top 3 highest-paid employees in each department.
Query:
SELECT
DepartmentId,
EmpName,
Salary,
RANK() OVER (PARTITION BY DepartmentId ORDER BY Salary DESC) AS SalaryRank
FROM Employees
WHERE Salary IS NOT NULL
Then wrap it to filter top 3:
SELECT *
FROM (
SELECT
DepartmentId,
EmpName,
Salary,
RANK() OVER (PARTITION BY DepartmentId ORDER BY Salary DESC) AS SalaryRank
FROM Employees
) AS Ranked
WHERE SalaryRank <= 3;
Explanation:
The RANK() function assigns ranking per department.
The outer query filters the top 3 salaries per department.
4. Simplifying Logic with Common Table Expressions (CTE)
Scenario:
Find employees who earn more than the average salary in their department (using CTE for clarity).
Query:
WITH DeptAverage AS (
SELECT
DepartmentId,
AVG(Salary) AS AvgSalary
FROM Employees
GROUP BY DepartmentId
)
SELECT
E.EmpName,
E.DepartmentId,
E.Salary,
D.AvgSalary
FROM Employees E
JOIN DeptAverage D ON E.DepartmentId = D.DepartmentId
WHERE E.Salary > D.AvgSalary;
Explanation:
The CTE (DeptAverage) simplifies complex nested subqueries, making the query more readable and maintainable.
5. Transforming Rows to Columns with PIVOT
Scenario:
Show total sales by product across different months.
Query:
SELECT *
FROM (
SELECT
ProductName,
DATENAME(MONTH, OrderDate) AS [Month],
(Quantity * UnitPrice) AS TotalSales
FROM OrderDetails OD
JOIN Orders O ON OD.OrderId = O.OrderId
JOIN Products P ON OD.ProductId = P.ProductId
) AS SourceTable
PIVOT (
SUM(TotalSales)
FOR [Month] IN ([January], [February], [March], [April], [May], [June])
) AS PivotTable;
Explanation:
This query pivots monthly sales data into columns, allowing easier visualization and reporting.
6. Recursive Queries with CTE
Scenario:
Retrieve a hierarchical list of employees under a specific manager.
Query:
WITH EmployeeHierarchy AS (
SELECT
EmpId, EmpName, ManagerId
FROM Employees
WHERE ManagerId IS NULL -- Top-level managers
UNION ALL
SELECT
E.EmpId, E.EmpName, E.ManagerId
FROM Employees E
INNER JOIN EmployeeHierarchy EH ON E.ManagerId = EH.EmpId
)
SELECT * FROM EmployeeHierarchy;
Explanation:
This recursive CTE walks through employee-manager relationships to display a full organizational hierarchy.
Performance Tip
When dealing with large datasets:
- Use indexes on join and filter columns.
- Avoid using SELECT *; only fetch required columns.
- Check execution plans using SQL Server Management Studio (SSMS).
- Use temp tables or CTEs for readability and modularization.
Conclusion
Complex SQL queries are powerful tools for solving real-world data problems — from business intelligence reports to analytics dashboards. By mastering subqueries, CTEs, window functions, and pivots, you can transform SQL Server from a data store into an insight engine.
Keep practicing on realistic datasets like AdventureWorks or Northwind — and soon, you’ll write elegant and efficient SQL like a pro!
Next Steps:
- Try rewriting one of your existing reports using a CTE.
- Use RANK() and PIVOT for analytics dashboards.
- Explore query optimization using SET STATISTICS IO, TIME ON.