SQL:SQL Window Functions: ROW_NUMBER, RANK, and OVER (PARTITION BY)
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:

ParameterTypeDescription
OVER()ClauseDefines window partitioning and ordering for function.
ROW_NUMBER()Window FunctionAssigns sequential integer rank to rows in each window.

Ready-to-Run Code Example

Executable in Compilra

Run 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

Run and test SQL on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

SQL Online Compiler