Learn Window Functions, CTEs, Recursive Queries, and Pivot/Unpivot
Master advanced SQL queries with this comprehensive guide. Learn how to use window functions, Common Table Expressions (CTEs), recursive queries, and pivot/unpivot operations. Practice ranking employees, handling hierarchical data, and summarizing sales by month.
1. Introduction
Advanced SQL queries allow you to perform complex data analysis, reporting, and hierarchical operations.
- Use window functions for ranking and analytics.
- Use CTEs and recursive queries for readable and reusable query structures.
- Pivot/unpivot operations help reshape data for reporting and dashboards.
2. Window Functions
Window functions perform calculations across a set of rows related to the current row without collapsing the result set.
Common Functions:
ROW_NUMBER()– Sequential numbering of rows.RANK()– Ranking with gaps for ties.DENSE_RANK()– Ranking without gaps for ties.NTILE(n)– Divides rows into n equal parts.
Example – Rank employees by salary in each department:
3. Common Table Expressions (CTEs)
CTEs allow you to create temporary result sets that can be referenced within a query.
Syntax:
Example – Hierarchical data (employees reporting structure):
4. Recursive Queries
- Recursive CTEs help traverse hierarchical data (e.g., org charts, categories).
- Base query defines the root level, recursive query references the CTE itself.
Example – Employee reporting chain:
5. Pivot / Unpivot Data
5.1 Pivot
- Converts rows into columns for summary reports.
Example – Pivot sales data per month:
5.2 Unpivot
- Converts columns into rows.
Example:
6. Practical Exercises
- Rank employees by salary in each department using ROW_NUMBER(), RANK(), DENSE_RANK().
- Create a CTE to list all employees in hierarchical order.
- Use a recursive CTE to display the full reporting chain of managers.
- Pivot monthly sales data for all employees to view columns as months.
- Unpivot pivoted sales data to restore the original row-wise format.
7. Tips for Beginners
- Window functions do not reduce rows; they just add analytic columns.
- Use CTEs for readable, maintainable queries instead of subqueries.
- Recursive CTEs are powerful for hierarchical data but test for infinite loops.
- Pivot/unpivot are ideal for reporting and dashboards.
- Combine these techniques with indexes and optimization for performance.
Next Step: After mastering advanced SQL queries, the next module is Data Types and Constraints, where you’ll learn to enforce data integrity using primary keys, foreign keys, unique, not null, and check constraints.