3. Modifying Data, Performance & Capstone

Views & Window Functions Basics

Save reusable queries as SQL Views (CREATE VIEW) and learn how Window Functions (ROW_NUMBER, RANK, running totals) calculate rankings without collapsing rows.

3 min readUpdated 2026-11-29
In This Lesson
  • Save complex reusable SELECT queries as virtual Views (CREATE VIEW)
  • Rank rows within categories using ROW_NUMBER() OVER (PARTITION BY ...)
  • Compute running totals without collapsing detail rows

Two SQL tools separate beginners from confident backend & analytics practitioners: Views (for reusable queries) and Window Functions (for rankings and running totals).

Saving Reusable Queries with CREATE VIEW

Suppose your dashboard runs the same 15-line JOIN + GROUP BY query in five places. Instead of copying it everywhere, save it as a View:

sql
CREATE VIEW course_enrollment_summary AS
SELECT
  c.id,
  c.title,
  c.category,
  COUNT(e.id) AS total_enrollments
FROM courses c
LEFT JOIN enrollments e ON e.course_id = c.id
GROUP BY c.id, c.title, c.category;

Now you can query that view like a clean virtual table:

sql
SELECT title, total_enrollments
FROM course_enrollment_summary
WHERE category = 'Programming'
ORDER BY total_enrollments DESC;
Views Don't Duplicate Data

A standard View stores only the SQL query—not a separate copy of the rows—so querying the view always reflects the latest live data.

Window Functions (OVER (...))

GROUP BY (Collapses Rows) vs Window OVER() (Preserves Rows)

GROUP BY category (4 rows → 2 rows)

Hardware | count=2 | avg=$62.00
Books | count=1 | avg=$29.00

Individual product names & prices are collapsed away.

ROW_NUMBER() OVER (PARTITION BY category)

Keyboard | Hardware | $89 | rank=1
USB-C Hub | Hardware | $35 | rank=2
Python Book | Books | $29 | rank=1

GROUP BY shrinks 4 products down to 2 category summary rows. Window functions attach category rank or running total onto every original product row.

GROUP BY collapses 10 rows into 1 summary row. Window functions let you compute rankings, previous-row comparisons, or running totals while keeping every individual row visible!

Look for the OVER (...) keyword:

1. ROW_NUMBER() vs RANK() vs DENSE_RANK()

When two items tie on price or score, pick the ranking function that matches your business rule:

FunctionRanks for [100, 100, 80]Best Use Case
ROW_NUMBER()1, 2, 3 (breaks ties arbitrarily)Strict pagination or picking exactly 1 winner per group
RANK()1, 1, 3 (leaves gap after tie)Competition leaderboards
DENSE_RANK()1, 1, 2 (no gaps after tie)Top-N distinct price/salary tiers
sql
SELECT
  title,
  category,
  estimated_hours,
  ROW_NUMBER() OVER (
    PARTITION BY category
    ORDER BY estimated_hours DESC
  ) AS rank_in_category
FROM courses;
  • PARTITION BY category restarts numbering at 1 for each category.
  • ORDER BY estimated_hours DESC decides who gets rank #1.

2. Running Totals & Previous-Row Comparisons (LAG / LEAD)

sql
-- Running total across chronological orders
SELECT
  ordered_at,
  amount,
  SUM(amount) OVER (ORDER BY ordered_at) AS running_revenue
FROM paid_orders;

-- Compare each order against the previous order's amount
SELECT
  id,
  ordered_at,
  amount,
  LAG(amount) OVER (ORDER BY ordered_at) AS previous_amount
FROM paid_orders;

Try It Yourself: Live Window Functions

Run both ROW_NUMBER() and a running price summary (SUM(...) OVER (...)) directly in SQLite:

SQL (SQLite)Live SQL: ROW_NUMBER(), DENSE_RANK() & Running Totals
Output

Click “Run Code” to execute this snippet right in your browser.

Quick Checkpoints

Check Your Understanding

What is the key difference between GROUP BY and a Window Function (OVER (...))?