bhylu.com

Advertisements

SQL Window Functions

A window function calculates across related rows while keeping the individual rows in the result. GROUP BY collapses rows into summaries; a window can attach a summary to each order without removing order detail.

Understand the idea

PARTITION BY starts a separate calculation for each customer. Unlike GROUP BY, it does not combine the customer's orders into one row. The result shows each order beside that customer's total. This is useful for comparisons, percentages, and report context, but the repeated total must not be summed again as if it were a new fact.

Where to try it

Run this example in the SQL playground. The lesson link loads the shop tables and sample rows before this query. Select Run when you are ready. Every run starts fresh, so your changes do not affect the website or a previous run.

SQLite sample data · MySQL / MariaDB sample data · See the sample tables

A worked example

SQLite

SELECT order_id, customer_id, total_cents,
       SUM(total_cents) OVER (PARTITION BY customer_id) AS customer_cents
FROM orders
ORDER BY customer_id, order_id;

Read the result

Mira's orders 101 and 103 each show customer_cents 3200. Dev's total is 1350 and Asha's is 250. Every source order remains present.

Try one change

Add COUNT(*) OVER (PARTITION BY customer_id) and explain why Mira's two rows both display 2.