Skip to content
Learn Netverks

Lesson

Step 21/36 58% through track

window-functions-postgresql

Window functions

Last reviewed May 28, 2026 Content v20260528
Track mode
sql_sandbox
Means
SQL sandbox
Reading
~1 min
Level
intermediate

This lesson

This lesson teaches Window functions: the SQL patterns, schema habits, and query reasoning you need before advancing in PostgreSQL.

Teams query Window functions on every PostgreSQL codebase—skipping it leaves gaps in debugging and data reviews.

You will apply Window functions in contexts like: Modern startups, geospatial apps, and analytics-friendly OLTP systems.

Copy Postgres SQL into psql, local PostgreSQL, or DB Fiddle (PostgreSQL dialect)—use \d and EXPLAIN ANALYZE where lessons show them. The in-browser lab ships later; psql is the practice path now.

When you can explain the previous lesson's ideas without copying example queries verbatim.

Window functions compute across related rows without collapsing the result set—ranking, running totals, and lead/lag comparisons.

ROW_NUMBER and RANK

SELECT
  id,
  customer_id,
  total,
  ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at DESC) AS rn
FROM orders;

Practice: Seed customers/orders tables from earlier lessons, then run queries in psql or DB Fiddle (PostgreSQL).

Running sums

SELECT
  created_at::date AS day,
  total,
  SUM(total) OVER (ORDER BY created_at) AS running_revenue
FROM orders;

LAG and LEAD

SELECT
  id,
  total,
  LAG(total) OVER (PARTITION BY customer_id ORDER BY created_at) AS prev_total
FROM orders;

Important interview questions and answers

  1. Q: Window vs GROUP BY?
    A: Window keeps detail rows; GROUP BY returns one row per group.
  2. Q: PARTITION BY?
    A: Defines groups over which the window frame is applied.

Self-check

  1. How do you rank orders per customer by date?
  2. What frame does ORDER BY inside OVER define?

Tip: ROW_NUMBER vs RANK—ties handled differently; pick intentionally.

Interview prep

PARTITION BY?

Defines groups for window calculations.

Window vs GROUP BY?

Window keeps detail rows; GROUP BY collapses.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • PARTITION BY pick?
  • ROWS vs RANGE?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump