Introduction
The OVER clause with PARTITION BY helps you group data into parts and perform calculations on each part separately, without losing the original rows.
SELECT column1, column2, aggregate_function() OVER (PARTITION BY column_to_group) AS alias_name FROM table_name;
SELECT employee_id, department_id, salary, AVG(salary) OVER (PARTITION BY department_id) AS avg_dept_salary FROM employees;
SELECT student_id, class_id, score, RANK() OVER (PARTITION BY class_id ORDER BY score DESC) AS class_rank FROM exam_results;
SELECT order_id, region, amount, SUM(amount) OVER (PARTITION BY region) AS total_region_sales FROM sales;
CREATE TABLE sales ( order_id INT, region VARCHAR(20), amount INT ); INSERT INTO sales VALUES (1, 'North', 100), (2, 'South', 150), (3, 'North', 200), (4, 'South', 50), (5, 'East', 300); SELECT order_id, region, amount, SUM(amount) OVER (PARTITION BY region) AS total_region_sales FROM sales ORDER BY order_id;
PARTITION BY clause do when used with the OVER clause in SQL?PARTITION BY clause groups rows based on column values, similar to grouping in real life like sorting students by class.OVER clause applies functions like SUM or ROW_NUMBER within each group separately, not on the whole table.OVER with PARTITION BY?PARTITION BY before ORDER BY inside the parentheses after OVER.SUM(sales) OVER (PARTITION BY department ORDER BY date). Others misplace PARTITION BY or OVER keywords.Employees with columns Department and Salary, what will the following query return?SELECT Department, Salary, RANK() OVER (PARTITION BY Department ORDER BY Salary DESC) AS SalaryRank FROM Employees;
RANK() function assigns ranks starting at 1 within each partition (department), ordered by salary descending.SELECT employee_id, department, SUM(salary) OVER PARTITION BY department FROM employees;
OVER clause must have parentheses enclosing PARTITION BY and other clauses.OVER (PARTITION BY department).OVER with PARTITION BY to achieve this?OVER (PARTITION BY class ...). RANK() orders descending for highest score first; AVG() just partitions by class.RANK() OVER (PARTITION BY class ORDER BY score DESC) and AVG(score) OVER (PARTITION BY class). Others have syntax errors or wrong order.Pass the test and this pattern moves unknown