SQL•Window Functions
SQL Window Functions: ROW_NUMBER, RANK, and OVER (PARTITION BY)
Window functions perform calculations across sets of table rows related to the current row without collapsing rows.
Syntax
SELECT col, ROW_NUMBER() OVER (PARTITION BY cat ORDER BY val DESC) FROM table;
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| OVER() | Clause | Defines window partitioning and ordering for function. |
| ROW_NUMBER() | Window Function | Assigns sequential integer rank to rows in each window. |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing SQL locally:
CREATE TABLE employee_salaries (
id INTEGER PRIMARY KEY,
department TEXT,
name TEXT,
salary REAL
);
INSERT INTO employee_salaries VALUES
(1, 'Engineering', 'Alex', 120000),
(2, 'Engineering', 'Sarah', 135000),
(3, 'Sales', 'Michael', 95000),
(4, 'Sales', 'Jessica', 110000);
-- Rank employees within their department by salary using ROW_NUMBER()
SELECT
department,
name,
salary,
ROW_NUMBER() OVER (
PARTITION BY department
ORDER BY salary DESC
) AS rank_in_dept
FROM employee_salaries;Expected Output:
department name salary rank_in_dept ----------- ------- -------- ------------ Engineering Sarah 135000.0 1 Engineering Alex 120000.0 2 Sales Jessica 110000.0 1 Sales Michael 95000.0 2
How It Works: Step-by-Step
- Lines 8-12: Inserts salaries across Engineering and Sales.
- Lines 18-22: ROW_NUMBER() OVER (PARTITION BY department ORDER BY salary DESC) ranks salaries per department.
Key Concepts
- Unlike GROUP BY, window functions retain individual row identities while computing group metrics.
- PARTITION BY divides rows into groups; ORDER BY sets ranking order inside the window.
Common Mistake: Confusing GROUP BY with PARTITION BY in window functions
GROUP BY collapses rows into a single summary row; PARTITION BY in OVER() keeps all original rows intact.
❌ Incorrect
// Using GROUP BY when individual row details are needed
✅ Correct
SELECT name, ROW_NUMBER() OVER (PARTITION BY dept) ...
Related SQL Tutorials & Compiler
SQL Dynamic Transactional CASE WHEN Metrics Query Logic
Implement dynamic transactional business logic and classification metrics in SQL using CASE WHEN expressions.
SQL GROUP BY and HAVING: Grouping and Post-Filter Aggregation
Group rows by categories with GROUP BY and filter aggregated groups using HAVING.
SQL Common Table Expressions (WITH Clause / CTEs)
Write clean, readable multi-step queries using Common Table Expressions (WITH).
SQL Online Compiler
Open in Compilra IDE
Run and test SQL on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.