Lab 05: Advanced JDBC — Window Functions & CTEs

Objective

Go beyond basic CRUD with SQLite: SQL window functions (RANK, SUM OVER), recursive and non-recursive CTEs, ON CONFLICT DO UPDATE upsert, CREATE INDEX performance, batch-insert 100 orders, and JSON extraction with json_extract().

Background

Window functions compute aggregates across a "window" of rows relative to each row — without collapsing the result set like GROUP BY. They're indispensable for rankings, running totals, moving averages, and percentile analysis. CTEs (WITH) make complex queries readable by naming sub-queries. These are standard SQL 2003 features supported by SQLite 3.25+, PostgreSQL, MySQL 8+, and SQL Server.

Time

35 minutes

Prerequisites

  • Practitioner Lab 10 (JDBC & SQLite)

Tools

  • Docker: zchencow/innozverse-java:latest

  • SQLite JDBC (via Maven)


Lab Instructions

Steps 1–8: Schema + batch insert, window RANK, running total SUM OVER, CTE rollup, JSON functions, upsert, partial index, Capstone

💡 Window functions don't reduce rows. Unlike GROUP BY which collapses N rows into 1, RANK() OVER(...) assigns a rank to every row while keeping all rows in the result. PARTITION BY category resets the rank counter for each category. ORDER BY SUM(total) DESC inside the window determines ranking direction. This is how you get "rank within group" without a self-join.

📸 Verified Output:


Summary

SQL Feature
Syntax
Use for

Window RANK

RANK() OVER(PARTITION BY x ORDER BY y)

Rank within group

Running total

SUM(col) OVER(ORDER BY x)

Cumulative sum

CTE

WITH name AS (SELECT ...)

Named sub-query

Upsert

ON CONFLICT(pk) DO UPDATE SET

Insert or update

JSON extract

json_extract(col, '$.key')

Query JSON column

Further Reading

Last updated