PIVOT and UNPIVOT in SELECT Statement

In reporting and analytics, we often need to rotate data — turning rows into columns or columns into rows.SQL provides two powerful operators for this purpose: PIVOT and UNPIVOT. Let’s explore them step by step with examples from the HR schema. Example 1: Pivoting Employee Count by Job and Department This query counts employees by […]

RANK, DENSE_RANK, and ROW_NUMBER in SELECT Statement

Ranking functions are part of SQL analytic functions and are widely used in reporting, analytics, and business intelligence. The most common ones are RANK, DENSE_RANK, and ROW_NUMBER. While they seem similar, their behavior differs when handling duplicate values. Let’s explore them through practical examples. Example 1: Ranking Employees by Salary within Each Department Here we […]

ROLLUP and CUBE in SELECT Statement

SQL provides powerful extensions to GROUP BY: ROLLUP and CUBE. These are extremely useful for building reports with subtotals and cross-tab summaries. Let’s see some practical examples. Example 1: Total Salaries with ROLLUP by Department and Job This query calculates total salaries: Output: The hierarchy is clear: job totals roll up into department totals, which […]