When a learner can reproduce a familiar example but a small variation causes confusion, the problem is usually an incomplete model rather than a lack of effort. The fastest useful response is to expose the hidden state and test one boundary at a time.
A SQL window function calculates across related rows while keeping each input row visible. Unlike GROUP BY, it does not collapse the result to one row per group; its meaning comes from the window’s partition, ordering and frame, so those three boundaries must be read separately. This guide begins with that mechanism, then develops it through worked traces, deliberate mistakes, explained practice and transfer decisions.
The aim is independent reasoning. A learner should be able to predict behaviour, locate the earliest wrong assumption, use a safe diagnostic procedure and defend a design choice in a new project.
Punggol families can use the guide in short sessions around homework, CCAs and rest. The activities are proposed learning exercises, not claims about a physical branch, timetable, class size, fee, school relationship or guaranteed result.
Use disposable data and repositories, preserve backups, and check version-sensitive details against the official source. Current documentation settles a technical contract; observation and explanation turn that contract into usable knowledge.
Find your next learning step
Choose the route that matches the present difficulty. Use the complete index for a systematic course.
Build the model
Chapters 1-4 . Begin here, then continue after the learner can predict, verify and explain.
Use the core tools
Chapters 5-8 . Begin here, then continue after the learner can predict, verify and explain.
Handle boundaries
Chapters 9-12 . Begin here, then continue after the learner can predict, verify and explain.
Debug and verify
Chapters 13-16 . Begin here, then continue after the learner can predict, verify and explain.
Transfer with judgment
Chapters 17-20 . Begin here, then continue after the learner can predict, verify and explain.
Open the full chapter index . Jump to capstone practice . Use the How Studying Works hub . Read the official documentation
Complete chapter index
Chapters 1-4 . Build the model
Chapters 5-8 . Use the core tools
Chapters 9-12 . Handle boundaries
Chapters 13-16 . Debug and verify
Chapters 17-20 . Transfer with judgment
Window functions add calculations to a row set without collapsing rows the way grouped aggregation does. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is reaching for GROUP BY and then trying to recover lost detail. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Write the desired output grain before selecting aggregation or a window.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
SELECT name,score,avg(score) OVER () FROM results;Explained result. Every result row remains, with the overall average repeated as context. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: test results. Predict the rule using student, subject, score and sitting date. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Window functions add calculations to a row set without collapsing rows the way grouped aggregation does.” Apply this procedure: Write the desired output grain before selecting aggregation or a window. The expected mechanism is: Every result row remains, with the overall average repeated as context. For the test results, add one near-miss that exposes reaching for GROUP BY and then trying to recover lost detail. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: reading progress. Contrast the rule using reader, book, date and pages completed. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Window functions add calculations to a row set without collapsing rows the way grouped aggregation does.” Apply this procedure: Write the desired output grain before selecting aggregation or a window. The expected mechanism is: Every result row remains, with the overall average repeated as context. For the reading progress, add one near-miss that exposes reaching for GROUP BY and then trying to recover lost detail. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: CCA attendance. Stress-test the rule using activity, participant, session date and attendance. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Window functions add calculations to a row set without collapsing rows the way grouped aggregation does.” Apply this procedure: Write the desired output grain before selecting aggregation or a window. The expected mechanism is: Every result row remains, with the overall average repeated as context. For the CCA attendance, add one near-miss that exposes reaching for GROUP BY and then trying to recover lost detail. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: weather observations. Explain the rule using station, timestamp, temperature and rainfall. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Window functions add calculations to a row set without collapsing rows the way grouped aggregation does.” Apply this procedure: Write the desired output grain before selecting aggregation or a window. The expected mechanism is: Every result row remains, with the overall average repeated as context. For the weather observations, add one near-miss that exposes reaching for GROUP BY and then trying to recover lost detail. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers reaching for GROUP BY and then trying to recover lost detail.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Write the desired output grain before selecting aggregation or a window.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny budget ledger with category, transaction date, amount and account. Include one ordinary case, one boundary and one deliberate failure caused by reaching for GROUP BY and then trying to recover lost detail. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: Window functions add calculations to a row set without collapsing rows the way grouped aggregation does. It shows a trace, not only a final value. The ordinary case should demonstrate “Every result row remains, with the overall average repeated as context.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Write the desired output grain before selecting aggregation or a window. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
OVER defines the row context for a window call; empty parentheses mean all rows in the virtual table. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is reading only the function name and ignoring its window specification. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Underline function, partition, order and frame as separate clauses.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
sum(amount) OVER ()Explained result. The total is calculated over every row visible to the query stage. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: CCA attendance. Contrast the rule using activity, participant, session date and attendance. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “OVER defines the row context for a window call; empty parentheses mean all rows in the virtual table.” Apply this procedure: Underline function, partition, order and frame as separate clauses. The expected mechanism is: The total is calculated over every row visible to the query stage. For the CCA attendance, add one near-miss that exposes reading only the function name and ignoring its window specification. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: weather observations. Stress-test the rule using station, timestamp, temperature and rainfall. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “OVER defines the row context for a window call; empty parentheses mean all rows in the virtual table.” Apply this procedure: Underline function, partition, order and frame as separate clauses. The expected mechanism is: The total is calculated over every row visible to the query stage. For the weather observations, add one near-miss that exposes reading only the function name and ignoring its window specification. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: revision evidence. Explain the rule using topic, attempt date, confidence and result. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “OVER defines the row context for a window call; empty parentheses mean all rows in the virtual table.” Apply this procedure: Underline function, partition, order and frame as separate clauses. The expected mechanism is: The total is calculated over every row visible to the query stage. For the revision evidence, add one near-miss that exposes reading only the function name and ignoring its window specification. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: budget ledger. Transfer the rule using category, transaction date, amount and account. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “OVER defines the row context for a window call; empty parentheses mean all rows in the virtual table.” Apply this procedure: Underline function, partition, order and frame as separate clauses. The expected mechanism is: The total is calculated over every row visible to the query stage. For the budget ledger, add one near-miss that exposes reading only the function name and ignoring its window specification. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers reading only the function name and ignoring its window specification.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Underline function, partition, order and frame as separate clauses.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny transport log with route, stop, time and passenger count. Include one ordinary case, one boundary and one deliberate failure caused by reading only the function name and ignoring its window specification. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: OVER defines the row context for a window call; empty parentheses mean all rows in the virtual table. It shows a trace, not only a final value. The ordinary case should demonstrate “The total is calculated over every row visible to the query stage.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Underline function, partition, order and frame as separate clauses. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
PARTITION BY divides the virtual table into independent calculation groups while preserving rows. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is confusing partitions with physical database partitions or GROUP BY output groups. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Trace one row and list exactly which peers share its partition.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
avg(score) OVER (PARTITION BY subject)Explained result. Each score row receives the average for its own subject. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: revision evidence. Stress-test the rule using topic, attempt date, confidence and result. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “PARTITION BY divides the virtual table into independent calculation groups while preserving rows.” Apply this procedure: Trace one row and list exactly which peers share its partition. The expected mechanism is: Each score row receives the average for its own subject. For the revision evidence, add one near-miss that exposes confusing partitions with physical database partitions or GROUP BY output groups. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: budget ledger. Explain the rule using category, transaction date, amount and account. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “PARTITION BY divides the virtual table into independent calculation groups while preserving rows.” Apply this procedure: Trace one row and list exactly which peers share its partition. The expected mechanism is: Each score row receives the average for its own subject. For the budget ledger, add one near-miss that exposes confusing partitions with physical database partitions or GROUP BY output groups. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: transport log. Transfer the rule using route, stop, time and passenger count. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “PARTITION BY divides the virtual table into independent calculation groups while preserving rows.” Apply this procedure: Trace one row and list exactly which peers share its partition. The expected mechanism is: Each score row receives the average for its own subject. For the transport log, add one near-miss that exposes confusing partitions with physical database partitions or GROUP BY output groups. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: project board. Predict the rule using team, task, update time and status. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “PARTITION BY divides the virtual table into independent calculation groups while preserving rows.” Apply this procedure: Trace one row and list exactly which peers share its partition. The expected mechanism is: Each score row receives the average for its own subject. For the project board, add one near-miss that exposes confusing partitions with physical database partitions or GROUP BY output groups. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers confusing partitions with physical database partitions or GROUP BY output groups.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Trace one row and list exactly which peers share its partition.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny project board with team, task, update time and status. Include one ordinary case, one boundary and one deliberate failure caused by confusing partitions with physical database partitions or GROUP BY output groups. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: PARTITION BY divides the virtual table into independent calculation groups while preserving rows. It shows a trace, not only a final value. The ordinary case should demonstrate “Each score row receives the average for its own subject.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Trace one row and list exactly which peers share its partition. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
ORDER BY inside OVER controls the analytic sequence; the query’s final ORDER BY controls displayed row order. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is assuming analytic order guarantees final presentation order. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Specify both when both meanings matter and compare their roles.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
row_number() OVER (ORDER BY score DESC)Explained result. Numbers follow descending scores, but the final SELECT still needs ORDER BY for guaranteed display order. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: transport log. Explain the rule using route, stop, time and passenger count. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “ORDER BY inside OVER controls the analytic sequence; the query’s final ORDER BY controls displayed row order.” Apply this procedure: Specify both when both meanings matter and compare their roles. The expected mechanism is: Numbers follow descending scores, but the final SELECT still needs ORDER BY for guaranteed display order. For the transport log, add one near-miss that exposes assuming analytic order guarantees final presentation order. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: project board. Transfer the rule using team, task, update time and status. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “ORDER BY inside OVER controls the analytic sequence; the query’s final ORDER BY controls displayed row order.” Apply this procedure: Specify both when both meanings matter and compare their roles. The expected mechanism is: Numbers follow descending scores, but the final SELECT still needs ORDER BY for guaranteed display order. For the project board, add one near-miss that exposes assuming analytic order guarantees final presentation order. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: test results. Predict the rule using student, subject, score and sitting date. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “ORDER BY inside OVER controls the analytic sequence; the query’s final ORDER BY controls displayed row order.” Apply this procedure: Specify both when both meanings matter and compare their roles. The expected mechanism is: Numbers follow descending scores, but the final SELECT still needs ORDER BY for guaranteed display order. For the test results, add one near-miss that exposes assuming analytic order guarantees final presentation order. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: reading progress. Contrast the rule using reader, book, date and pages completed. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “ORDER BY inside OVER controls the analytic sequence; the query’s final ORDER BY controls displayed row order.” Apply this procedure: Specify both when both meanings matter and compare their roles. The expected mechanism is: Numbers follow descending scores, but the final SELECT still needs ORDER BY for guaranteed display order. For the reading progress, add one near-miss that exposes assuming analytic order guarantees final presentation order. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers assuming analytic order guarantees final presentation order.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Specify both when both meanings matter and compare their roles.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny test results with student, subject, score and sitting date. Include one ordinary case, one boundary and one deliberate failure caused by assuming analytic order guarantees final presentation order. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: ORDER BY inside OVER controls the analytic sequence; the query’s final ORDER BY controls displayed row order. It shows a trace, not only a final value. The ordinary case should demonstrate “Numbers follow descending scores, but the final SELECT still needs ORDER BY for guaranteed display order.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Specify both when both meanings matter and compare their roles. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
ROW_NUMBER gives consecutive numbers within each partition according to the window order. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is using it for top-one selection without a deterministic tie-breaker. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Add a stable secondary key and filter in an outer query.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
row_number() OVER (PARTITION BY subject ORDER BY score DESC,id)Explained result. Each subject receives a deterministic sequence when id resolves equal scores. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: test results. Transfer the rule using student, subject, score and sitting date. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “ROW_NUMBER gives consecutive numbers within each partition according to the window order.” Apply this procedure: Add a stable secondary key and filter in an outer query. The expected mechanism is: Each subject receives a deterministic sequence when id resolves equal scores. For the test results, add one near-miss that exposes using it for top-one selection without a deterministic tie-breaker. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: reading progress. Predict the rule using reader, book, date and pages completed. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “ROW_NUMBER gives consecutive numbers within each partition according to the window order.” Apply this procedure: Add a stable secondary key and filter in an outer query. The expected mechanism is: Each subject receives a deterministic sequence when id resolves equal scores. For the reading progress, add one near-miss that exposes using it for top-one selection without a deterministic tie-breaker. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: CCA attendance. Contrast the rule using activity, participant, session date and attendance. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “ROW_NUMBER gives consecutive numbers within each partition according to the window order.” Apply this procedure: Add a stable secondary key and filter in an outer query. The expected mechanism is: Each subject receives a deterministic sequence when id resolves equal scores. For the CCA attendance, add one near-miss that exposes using it for top-one selection without a deterministic tie-breaker. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: weather observations. Stress-test the rule using station, timestamp, temperature and rainfall. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “ROW_NUMBER gives consecutive numbers within each partition according to the window order.” Apply this procedure: Add a stable secondary key and filter in an outer query. The expected mechanism is: Each subject receives a deterministic sequence when id resolves equal scores. For the weather observations, add one near-miss that exposes using it for top-one selection without a deterministic tie-breaker. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers using it for top-one selection without a deterministic tie-breaker.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Add a stable secondary key and filter in an outer query.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny reading progress with reader, book, date and pages completed. Include one ordinary case, one boundary and one deliberate failure caused by using it for top-one selection without a deterministic tie-breaker. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: ROW_NUMBER gives consecutive numbers within each partition according to the window order. It shows a trace, not only a final value. The ordinary case should demonstrate “Each subject receives a deterministic sequence when id resolves equal scores.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Add a stable secondary key and filter in an outer query. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
RANK leaves gaps after ties, while DENSE_RANK advances by one distinct ordered value. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is choosing the function before agreeing what the next rank should be. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Create a 90,90,80 example and state the expected sequence in words.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
rank() OVER (ORDER BY score DESC)Explained result. The ranks are 1,1,3; dense_rank would produce 1,1,2. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: CCA attendance. Predict the rule using activity, participant, session date and attendance. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “RANK leaves gaps after ties, while DENSE_RANK advances by one distinct ordered value.” Apply this procedure: Create a 90,90,80 example and state the expected sequence in words. The expected mechanism is: The ranks are 1,1,3; dense_rank would produce 1,1,2. For the CCA attendance, add one near-miss that exposes choosing the function before agreeing what the next rank should be. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: weather observations. Contrast the rule using station, timestamp, temperature and rainfall. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “RANK leaves gaps after ties, while DENSE_RANK advances by one distinct ordered value.” Apply this procedure: Create a 90,90,80 example and state the expected sequence in words. The expected mechanism is: The ranks are 1,1,3; dense_rank would produce 1,1,2. For the weather observations, add one near-miss that exposes choosing the function before agreeing what the next rank should be. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: revision evidence. Stress-test the rule using topic, attempt date, confidence and result. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “RANK leaves gaps after ties, while DENSE_RANK advances by one distinct ordered value.” Apply this procedure: Create a 90,90,80 example and state the expected sequence in words. The expected mechanism is: The ranks are 1,1,3; dense_rank would produce 1,1,2. For the revision evidence, add one near-miss that exposes choosing the function before agreeing what the next rank should be. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: budget ledger. Explain the rule using category, transaction date, amount and account. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “RANK leaves gaps after ties, while DENSE_RANK advances by one distinct ordered value.” Apply this procedure: Create a 90,90,80 example and state the expected sequence in words. The expected mechanism is: The ranks are 1,1,3; dense_rank would produce 1,1,2. For the budget ledger, add one near-miss that exposes choosing the function before agreeing what the next rank should be. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers choosing the function before agreeing what the next rank should be.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Create a 90,90,80 example and state the expected sequence in words.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny CCA attendance with activity, participant, session date and attendance. Include one ordinary case, one boundary and one deliberate failure caused by choosing the function before agreeing what the next rank should be. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: RANK leaves gaps after ties, while DENSE_RANK advances by one distinct ordered value. It shows a trace, not only a final value. The ordinary case should demonstrate “The ranks are 1,1,3; dense_rank would produce 1,1,2.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Create a 90,90,80 example and state the expected sequence in words. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
An ordered aggregate window can produce a cumulative result, but the exact included rows depend on its frame. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is calling every ordered SUM a row-by-row running total without reading peer behaviour. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. State the frame explicitly when duplicate order values matter.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
sum(amount) OVER (ORDER BY day ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)Explained result. Each row includes itself and all earlier rows in the declared order. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: revision evidence. Contrast the rule using topic, attempt date, confidence and result. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “An ordered aggregate window can produce a cumulative result, but the exact included rows depend on its frame.” Apply this procedure: State the frame explicitly when duplicate order values matter. The expected mechanism is: Each row includes itself and all earlier rows in the declared order. For the revision evidence, add one near-miss that exposes calling every ordered SUM a row-by-row running total without reading peer behaviour. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: budget ledger. Stress-test the rule using category, transaction date, amount and account. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “An ordered aggregate window can produce a cumulative result, but the exact included rows depend on its frame.” Apply this procedure: State the frame explicitly when duplicate order values matter. The expected mechanism is: Each row includes itself and all earlier rows in the declared order. For the budget ledger, add one near-miss that exposes calling every ordered SUM a row-by-row running total without reading peer behaviour. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: transport log. Explain the rule using route, stop, time and passenger count. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “An ordered aggregate window can produce a cumulative result, but the exact included rows depend on its frame.” Apply this procedure: State the frame explicitly when duplicate order values matter. The expected mechanism is: Each row includes itself and all earlier rows in the declared order. For the transport log, add one near-miss that exposes calling every ordered SUM a row-by-row running total without reading peer behaviour. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: project board. Transfer the rule using team, task, update time and status. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “An ordered aggregate window can produce a cumulative result, but the exact included rows depend on its frame.” Apply this procedure: State the frame explicitly when duplicate order values matter. The expected mechanism is: Each row includes itself and all earlier rows in the declared order. For the project board, add one near-miss that exposes calling every ordered SUM a row-by-row running total without reading peer behaviour. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers calling every ordered SUM a row-by-row running total without reading peer behaviour.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “State the frame explicitly when duplicate order values matter.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny weather observations with station, timestamp, temperature and rainfall. Include one ordinary case, one boundary and one deliberate failure caused by calling every ordered SUM a row-by-row running total without reading peer behaviour. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: An ordered aggregate window can produce a cumulative result, but the exact included rows depend on its frame. It shows a trace, not only a final value. The ordinary case should demonstrate “Each row includes itself and all earlier rows in the declared order.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: State the frame explicitly when duplicate order values matter. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
With window ordering, the default frame commonly includes rows from the partition start through the current row’s peers. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is expecting duplicate order keys to advance one physical row at a time. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Compare the default with an explicit ROWS frame using tied values.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
sum(points) OVER (ORDER BY round)Explained result. Rows sharing the same round can share a cumulative value under the default peer-aware frame. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: transport log. Stress-test the rule using route, stop, time and passenger count. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “With window ordering, the default frame commonly includes rows from the partition start through the current row’s peers.” Apply this procedure: Compare the default with an explicit ROWS frame using tied values. The expected mechanism is: Rows sharing the same round can share a cumulative value under the default peer-aware frame. For the transport log, add one near-miss that exposes expecting duplicate order keys to advance one physical row at a time. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: project board. Explain the rule using team, task, update time and status. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “With window ordering, the default frame commonly includes rows from the partition start through the current row’s peers.” Apply this procedure: Compare the default with an explicit ROWS frame using tied values. The expected mechanism is: Rows sharing the same round can share a cumulative value under the default peer-aware frame. For the project board, add one near-miss that exposes expecting duplicate order keys to advance one physical row at a time. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: test results. Transfer the rule using student, subject, score and sitting date. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “With window ordering, the default frame commonly includes rows from the partition start through the current row’s peers.” Apply this procedure: Compare the default with an explicit ROWS frame using tied values. The expected mechanism is: Rows sharing the same round can share a cumulative value under the default peer-aware frame. For the test results, add one near-miss that exposes expecting duplicate order keys to advance one physical row at a time. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: reading progress. Predict the rule using reader, book, date and pages completed. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “With window ordering, the default frame commonly includes rows from the partition start through the current row’s peers.” Apply this procedure: Compare the default with an explicit ROWS frame using tied values. The expected mechanism is: Rows sharing the same round can share a cumulative value under the default peer-aware frame. For the reading progress, add one near-miss that exposes expecting duplicate order keys to advance one physical row at a time. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers expecting duplicate order keys to advance one physical row at a time.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Compare the default with an explicit ROWS frame using tied values.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny revision evidence with topic, attempt date, confidence and result. Include one ordinary case, one boundary and one deliberate failure caused by expecting duplicate order keys to advance one physical row at a time. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: With window ordering, the default frame commonly includes rows from the partition start through the current row’s peers. It shows a trace, not only a final value. The ordinary case should demonstrate “Rows sharing the same round can share a cumulative value under the default peer-aware frame.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Compare the default with an explicit ROWS frame using tied values. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
Frame modes count physical rows, ordering-value ranges or peer groups respectively, subject to dialect support. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is selecting a frame keyword from appearance rather than the analytical question. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Describe the unit being accumulated before writing the frame.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
ROWS BETWEEN 2 PRECEDING AND CURRENT ROWExplained result. The frame contains at most the current physical row plus two preceding rows. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: test results. Explain the rule using student, subject, score and sitting date. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Frame modes count physical rows, ordering-value ranges or peer groups respectively, subject to dialect support.” Apply this procedure: Describe the unit being accumulated before writing the frame. The expected mechanism is: The frame contains at most the current physical row plus two preceding rows. For the test results, add one near-miss that exposes selecting a frame keyword from appearance rather than the analytical question. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: reading progress. Transfer the rule using reader, book, date and pages completed. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Frame modes count physical rows, ordering-value ranges or peer groups respectively, subject to dialect support.” Apply this procedure: Describe the unit being accumulated before writing the frame. The expected mechanism is: The frame contains at most the current physical row plus two preceding rows. For the reading progress, add one near-miss that exposes selecting a frame keyword from appearance rather than the analytical question. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: CCA attendance. Predict the rule using activity, participant, session date and attendance. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Frame modes count physical rows, ordering-value ranges or peer groups respectively, subject to dialect support.” Apply this procedure: Describe the unit being accumulated before writing the frame. The expected mechanism is: The frame contains at most the current physical row plus two preceding rows. For the CCA attendance, add one near-miss that exposes selecting a frame keyword from appearance rather than the analytical question. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: weather observations. Contrast the rule using station, timestamp, temperature and rainfall. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Frame modes count physical rows, ordering-value ranges or peer groups respectively, subject to dialect support.” Apply this procedure: Describe the unit being accumulated before writing the frame. The expected mechanism is: The frame contains at most the current physical row plus two preceding rows. For the weather observations, add one near-miss that exposes selecting a frame keyword from appearance rather than the analytical question. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers selecting a frame keyword from appearance rather than the analytical question.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Describe the unit being accumulated before writing the frame.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny budget ledger with category, transaction date, amount and account. Include one ordinary case, one boundary and one deliberate failure caused by selecting a frame keyword from appearance rather than the analytical question. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: Frame modes count physical rows, ordering-value ranges or peer groups respectively, subject to dialect support. It shows a trace, not only a final value. The ordinary case should demonstrate “The frame contains at most the current physical row plus two preceding rows.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Describe the unit being accumulated before writing the frame. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
LAG returns a value from a preceding row in the window order, with optional offset and default. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is subtracting from a previous row without deterministic chronological order. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Partition by entity and order by a stable timestamp plus key.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
score-lag(score) OVER (PARTITION BY student ORDER BY attempt_date,id)Explained result. Each attempt can be compared with the student’s preceding ordered attempt. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: CCA attendance. Transfer the rule using activity, participant, session date and attendance. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “LAG returns a value from a preceding row in the window order, with optional offset and default.” Apply this procedure: Partition by entity and order by a stable timestamp plus key. The expected mechanism is: Each attempt can be compared with the student’s preceding ordered attempt. For the CCA attendance, add one near-miss that exposes subtracting from a previous row without deterministic chronological order. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: weather observations. Predict the rule using station, timestamp, temperature and rainfall. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “LAG returns a value from a preceding row in the window order, with optional offset and default.” Apply this procedure: Partition by entity and order by a stable timestamp plus key. The expected mechanism is: Each attempt can be compared with the student’s preceding ordered attempt. For the weather observations, add one near-miss that exposes subtracting from a previous row without deterministic chronological order. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: revision evidence. Contrast the rule using topic, attempt date, confidence and result. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “LAG returns a value from a preceding row in the window order, with optional offset and default.” Apply this procedure: Partition by entity and order by a stable timestamp plus key. The expected mechanism is: Each attempt can be compared with the student’s preceding ordered attempt. For the revision evidence, add one near-miss that exposes subtracting from a previous row without deterministic chronological order. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: budget ledger. Stress-test the rule using category, transaction date, amount and account. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “LAG returns a value from a preceding row in the window order, with optional offset and default.” Apply this procedure: Partition by entity and order by a stable timestamp plus key. The expected mechanism is: Each attempt can be compared with the student’s preceding ordered attempt. For the budget ledger, add one near-miss that exposes subtracting from a previous row without deterministic chronological order. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers subtracting from a previous row without deterministic chronological order.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Partition by entity and order by a stable timestamp plus key.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny transport log with route, stop, time and passenger count. Include one ordinary case, one boundary and one deliberate failure caused by subtracting from a previous row without deterministic chronological order. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: LAG returns a value from a preceding row in the window order, with optional offset and default. It shows a trace, not only a final value. The ordinary case should demonstrate “Each attempt can be compared with the student’s preceding ordered attempt.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Partition by entity and order by a stable timestamp plus key. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
LEAD exposes a following row for gap, transition or next-event analysis. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is interpreting NULL as zero when there is no later row. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Choose and document an explicit default only when the domain supports it.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
lead(stop) OVER (PARTITION BY trip ORDER BY sequence)Explained result. Each stop row can show the next stop; the final one has no following value. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: revision evidence. Predict the rule using topic, attempt date, confidence and result. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “LEAD exposes a following row for gap, transition or next-event analysis.” Apply this procedure: Choose and document an explicit default only when the domain supports it. The expected mechanism is: Each stop row can show the next stop; the final one has no following value. For the revision evidence, add one near-miss that exposes interpreting NULL as zero when there is no later row. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: budget ledger. Contrast the rule using category, transaction date, amount and account. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “LEAD exposes a following row for gap, transition or next-event analysis.” Apply this procedure: Choose and document an explicit default only when the domain supports it. The expected mechanism is: Each stop row can show the next stop; the final one has no following value. For the budget ledger, add one near-miss that exposes interpreting NULL as zero when there is no later row. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: transport log. Stress-test the rule using route, stop, time and passenger count. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “LEAD exposes a following row for gap, transition or next-event analysis.” Apply this procedure: Choose and document an explicit default only when the domain supports it. The expected mechanism is: Each stop row can show the next stop; the final one has no following value. For the transport log, add one near-miss that exposes interpreting NULL as zero when there is no later row. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: project board. Explain the rule using team, task, update time and status. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “LEAD exposes a following row for gap, transition or next-event analysis.” Apply this procedure: Choose and document an explicit default only when the domain supports it. The expected mechanism is: Each stop row can show the next stop; the final one has no following value. For the project board, add one near-miss that exposes interpreting NULL as zero when there is no later row. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers interpreting NULL as zero when there is no later row.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Choose and document an explicit default only when the domain supports it.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny project board with team, task, update time and status. Include one ordinary case, one boundary and one deliberate failure caused by interpreting NULL as zero when there is no later row. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: LEAD exposes a following row for gap, transition or next-event analysis. It shows a trace, not only a final value. The ordinary case should demonstrate “Each stop row can show the next stop; the final one has no following value.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Choose and document an explicit default only when the domain supports it. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
FIRST_VALUE and LAST_VALUE select within the current frame, so LAST_VALUE often surprises when the frame ends at the current row. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is expecting LAST_VALUE to mean the partition’s final row automatically. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Declare a full-partition frame when that is the intended meaning.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
last_value(score) OVER (PARTITION BY student ORDER BY attempt ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)Explained result. Every attempt receives the student’s final ordered score. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: transport log. Contrast the rule using route, stop, time and passenger count. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “FIRST_VALUE and LAST_VALUE select within the current frame, so LAST_VALUE often surprises when the frame ends at the current row.” Apply this procedure: Declare a full-partition frame when that is the intended meaning. The expected mechanism is: Every attempt receives the student’s final ordered score. For the transport log, add one near-miss that exposes expecting LAST_VALUE to mean the partition’s final row automatically. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: project board. Stress-test the rule using team, task, update time and status. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “FIRST_VALUE and LAST_VALUE select within the current frame, so LAST_VALUE often surprises when the frame ends at the current row.” Apply this procedure: Declare a full-partition frame when that is the intended meaning. The expected mechanism is: Every attempt receives the student’s final ordered score. For the project board, add one near-miss that exposes expecting LAST_VALUE to mean the partition’s final row automatically. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: test results. Explain the rule using student, subject, score and sitting date. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “FIRST_VALUE and LAST_VALUE select within the current frame, so LAST_VALUE often surprises when the frame ends at the current row.” Apply this procedure: Declare a full-partition frame when that is the intended meaning. The expected mechanism is: Every attempt receives the student’s final ordered score. For the test results, add one near-miss that exposes expecting LAST_VALUE to mean the partition’s final row automatically. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: reading progress. Transfer the rule using reader, book, date and pages completed. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “FIRST_VALUE and LAST_VALUE select within the current frame, so LAST_VALUE often surprises when the frame ends at the current row.” Apply this procedure: Declare a full-partition frame when that is the intended meaning. The expected mechanism is: Every attempt receives the student’s final ordered score. For the reading progress, add one near-miss that exposes expecting LAST_VALUE to mean the partition’s final row automatically. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers expecting LAST_VALUE to mean the partition’s final row automatically.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Declare a full-partition frame when that is the intended meaning.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny test results with student, subject, score and sitting date. Include one ordinary case, one boundary and one deliberate failure caused by expecting LAST_VALUE to mean the partition’s final row automatically. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: FIRST_VALUE and LAST_VALUE select within the current frame, so LAST_VALUE often surprises when the frame ends at the current row. It shows a trace, not only a final value. The ordinary case should demonstrate “Every attempt receives the student’s final ordered score.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Declare a full-partition frame when that is the intended meaning. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
Ordinary aggregates such as sum, avg, min and max act as window functions when followed by OVER. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is adding GROUP BY unnecessarily and changing the result grain. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Keep the detailed FROM/WHERE row set and add window context deliberately.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
amount/sum(amount) OVER (PARTITION BY category)Explained result. Each transaction can express its share of the category total. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: test results. Stress-test the rule using student, subject, score and sitting date. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Ordinary aggregates such as sum, avg, min and max act as window functions when followed by OVER.” Apply this procedure: Keep the detailed FROM/WHERE row set and add window context deliberately. The expected mechanism is: Each transaction can express its share of the category total. For the test results, add one near-miss that exposes adding GROUP BY unnecessarily and changing the result grain. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: reading progress. Explain the rule using reader, book, date and pages completed. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Ordinary aggregates such as sum, avg, min and max act as window functions when followed by OVER.” Apply this procedure: Keep the detailed FROM/WHERE row set and add window context deliberately. The expected mechanism is: Each transaction can express its share of the category total. For the reading progress, add one near-miss that exposes adding GROUP BY unnecessarily and changing the result grain. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: CCA attendance. Transfer the rule using activity, participant, session date and attendance. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Ordinary aggregates such as sum, avg, min and max act as window functions when followed by OVER.” Apply this procedure: Keep the detailed FROM/WHERE row set and add window context deliberately. The expected mechanism is: Each transaction can express its share of the category total. For the CCA attendance, add one near-miss that exposes adding GROUP BY unnecessarily and changing the result grain. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: weather observations. Predict the rule using station, timestamp, temperature and rainfall. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Ordinary aggregates such as sum, avg, min and max act as window functions when followed by OVER.” Apply this procedure: Keep the detailed FROM/WHERE row set and add window context deliberately. The expected mechanism is: Each transaction can express its share of the category total. For the weather observations, add one near-miss that exposes adding GROUP BY unnecessarily and changing the result grain. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers adding GROUP BY unnecessarily and changing the result grain.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Keep the detailed FROM/WHERE row set and add window context deliberately.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny reading progress with reader, book, date and pages completed. Include one ordinary case, one boundary and one deliberate failure caused by adding GROUP BY unnecessarily and changing the result grain. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: Ordinary aggregates such as sum, avg, min and max act as window functions when followed by OVER. It shows a trace, not only a final value. The ordinary case should demonstrate “Each transaction can express its share of the category total.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Keep the detailed FROM/WHERE row set and add window context deliberately. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
A WINDOW clause can name a shared specification so several functions use the same partition and order. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is copying long specifications and letting one version diverge. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Name the common base and override only allowed, intentional parts.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
WINDOW w AS (PARTITION BY student ORDER BY attempt_date)Explained result. Multiple calculations can reuse one reviewed analytic ordering. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: CCA attendance. Explain the rule using activity, participant, session date and attendance. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A WINDOW clause can name a shared specification so several functions use the same partition and order.” Apply this procedure: Name the common base and override only allowed, intentional parts. The expected mechanism is: Multiple calculations can reuse one reviewed analytic ordering. For the CCA attendance, add one near-miss that exposes copying long specifications and letting one version diverge. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: weather observations. Transfer the rule using station, timestamp, temperature and rainfall. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A WINDOW clause can name a shared specification so several functions use the same partition and order.” Apply this procedure: Name the common base and override only allowed, intentional parts. The expected mechanism is: Multiple calculations can reuse one reviewed analytic ordering. For the weather observations, add one near-miss that exposes copying long specifications and letting one version diverge. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: revision evidence. Predict the rule using topic, attempt date, confidence and result. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A WINDOW clause can name a shared specification so several functions use the same partition and order.” Apply this procedure: Name the common base and override only allowed, intentional parts. The expected mechanism is: Multiple calculations can reuse one reviewed analytic ordering. For the revision evidence, add one near-miss that exposes copying long specifications and letting one version diverge. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: budget ledger. Contrast the rule using category, transaction date, amount and account. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “A WINDOW clause can name a shared specification so several functions use the same partition and order.” Apply this procedure: Name the common base and override only allowed, intentional parts. The expected mechanism is: Multiple calculations can reuse one reviewed analytic ordering. For the budget ledger, add one near-miss that exposes copying long specifications and letting one version diverge. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers copying long specifications and letting one version diverge.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Name the common base and override only allowed, intentional parts.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny CCA attendance with activity, participant, session date and attendance. Include one ordinary case, one boundary and one deliberate failure caused by copying long specifications and letting one version diverge. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: A WINDOW clause can name a shared specification so several functions use the same partition and order. It shows a trace, not only a final value. The ordinary case should demonstrate “Multiple calculations can reuse one reviewed analytic ordering.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Name the common base and override only allowed, intentional parts. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
One SELECT may contain several windows with different partitions, orders or frames. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is assuming all window expressions share one invisible global definition. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Annotate each calculation with its exact population and sequence.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
avg(score) OVER (PARTITION BY subject), avg(score) OVER ()Explained result. A row can carry both subject context and overall context. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: revision evidence. Transfer the rule using topic, attempt date, confidence and result. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “One SELECT may contain several windows with different partitions, orders or frames.” Apply this procedure: Annotate each calculation with its exact population and sequence. The expected mechanism is: A row can carry both subject context and overall context. For the revision evidence, add one near-miss that exposes assuming all window expressions share one invisible global definition. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: budget ledger. Predict the rule using category, transaction date, amount and account. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “One SELECT may contain several windows with different partitions, orders or frames.” Apply this procedure: Annotate each calculation with its exact population and sequence. The expected mechanism is: A row can carry both subject context and overall context. For the budget ledger, add one near-miss that exposes assuming all window expressions share one invisible global definition. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: transport log. Contrast the rule using route, stop, time and passenger count. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “One SELECT may contain several windows with different partitions, orders or frames.” Apply this procedure: Annotate each calculation with its exact population and sequence. The expected mechanism is: A row can carry both subject context and overall context. For the transport log, add one near-miss that exposes assuming all window expressions share one invisible global definition. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: project board. Stress-test the rule using team, task, update time and status. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “One SELECT may contain several windows with different partitions, orders or frames.” Apply this procedure: Annotate each calculation with its exact population and sequence. The expected mechanism is: A row can carry both subject context and overall context. For the project board, add one near-miss that exposes assuming all window expressions share one invisible global definition. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers assuming all window expressions share one invisible global definition.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Annotate each calculation with its exact population and sequence.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny weather observations with station, timestamp, temperature and rainfall. Include one ordinary case, one boundary and one deliberate failure caused by assuming all window expressions share one invisible global definition. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: One SELECT may contain several windows with different partitions, orders or frames. It shows a trace, not only a final value. The ordinary case should demonstrate “A row can carry both subject context and overall context.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Annotate each calculation with its exact population and sequence. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
CHAPTER 16 OF 20 . Debug and verify
16. Filtering window results needs a later query stage
In PostgreSQL, window functions run after WHERE and GROUP BY, so filtering their results requires a subquery or CTE. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is placing row_number directly in WHERE and expecting it to exist there. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Calculate in an inner query, then filter the named result outside.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
WITH ranked AS (...) SELECT * FROM ranked WHERE rn<=3;Explained result. The outer query can filter the already-computed window value. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: transport log. Predict the rule using route, stop, time and passenger count. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “In PostgreSQL, window functions run after WHERE and GROUP BY, so filtering their results requires a subquery or CTE.” Apply this procedure: Calculate in an inner query, then filter the named result outside. The expected mechanism is: The outer query can filter the already-computed window value. For the transport log, add one near-miss that exposes placing row_number directly in WHERE and expecting it to exist there. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: project board. Contrast the rule using team, task, update time and status. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “In PostgreSQL, window functions run after WHERE and GROUP BY, so filtering their results requires a subquery or CTE.” Apply this procedure: Calculate in an inner query, then filter the named result outside. The expected mechanism is: The outer query can filter the already-computed window value. For the project board, add one near-miss that exposes placing row_number directly in WHERE and expecting it to exist there. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: test results. Stress-test the rule using student, subject, score and sitting date. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “In PostgreSQL, window functions run after WHERE and GROUP BY, so filtering their results requires a subquery or CTE.” Apply this procedure: Calculate in an inner query, then filter the named result outside. The expected mechanism is: The outer query can filter the already-computed window value. For the test results, add one near-miss that exposes placing row_number directly in WHERE and expecting it to exist there. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: reading progress. Explain the rule using reader, book, date and pages completed. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “In PostgreSQL, window functions run after WHERE and GROUP BY, so filtering their results requires a subquery or CTE.” Apply this procedure: Calculate in an inner query, then filter the named result outside. The expected mechanism is: The outer query can filter the already-computed window value. For the reading progress, add one near-miss that exposes placing row_number directly in WHERE and expecting it to exist there. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers placing row_number directly in WHERE and expecting it to exist there.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Calculate in an inner query, then filter the named result outside.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny revision evidence with topic, attempt date, confidence and result. Include one ordinary case, one boundary and one deliberate failure caused by placing row_number directly in WHERE and expecting it to exist there. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: In PostgreSQL, window functions run after WHERE and GROUP BY, so filtering their results requires a subquery or CTE. It shows a trace, not only a final value. The ordinary case should demonstrate “The outer query can filter the already-computed window value.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Calculate in an inner query, then filter the named result outside. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
NULL placement affects analytic order and may be controlled with NULLS FIRST or NULLS LAST in supporting dialects. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is letting default NULL ordering silently choose the first or latest record. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. State how missing timestamps or scores should rank.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
ORDER BY submitted_at DESC NULLS LASTExplained result. Missing submission times are placed after known times in the analytic order. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: test results. Contrast the rule using student, subject, score and sitting date. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “NULL placement affects analytic order and may be controlled with NULLS FIRST or NULLS LAST in supporting dialects.” Apply this procedure: State how missing timestamps or scores should rank. The expected mechanism is: Missing submission times are placed after known times in the analytic order. For the test results, add one near-miss that exposes letting default NULL ordering silently choose the first or latest record. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: reading progress. Stress-test the rule using reader, book, date and pages completed. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “NULL placement affects analytic order and may be controlled with NULLS FIRST or NULLS LAST in supporting dialects.” Apply this procedure: State how missing timestamps or scores should rank. The expected mechanism is: Missing submission times are placed after known times in the analytic order. For the reading progress, add one near-miss that exposes letting default NULL ordering silently choose the first or latest record. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: CCA attendance. Explain the rule using activity, participant, session date and attendance. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “NULL placement affects analytic order and may be controlled with NULLS FIRST or NULLS LAST in supporting dialects.” Apply this procedure: State how missing timestamps or scores should rank. The expected mechanism is: Missing submission times are placed after known times in the analytic order. For the CCA attendance, add one near-miss that exposes letting default NULL ordering silently choose the first or latest record. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: weather observations. Transfer the rule using station, timestamp, temperature and rainfall. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “NULL placement affects analytic order and may be controlled with NULLS FIRST or NULLS LAST in supporting dialects.” Apply this procedure: State how missing timestamps or scores should rank. The expected mechanism is: Missing submission times are placed after known times in the analytic order. For the weather observations, add one near-miss that exposes letting default NULL ordering silently choose the first or latest record. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers letting default NULL ordering silently choose the first or latest record.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “State how missing timestamps or scores should rank.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny budget ledger with category, transaction date, amount and account. Include one ordinary case, one boundary and one deliberate failure caused by letting default NULL ordering silently choose the first or latest record. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: NULL placement affects analytic order and may be controlled with NULLS FIRST or NULLS LAST in supporting dialects. It shows a trace, not only a final value. The ordinary case should demonstrate “Missing submission times are placed after known times in the analytic order.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: State how missing timestamps or scores should rank. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
If ordered values tie and no stable secondary key exists, row_number, lag and frame-sensitive results may vary. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is calling a result deterministic because one test run looked stable. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Add a unique tie-breaker or accept and document peer-level nondeterminism.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
ORDER BY score DESC, attempt_idExplained result. attempt_id turns equal scores into a stable total order. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: CCA attendance. Stress-test the rule using activity, participant, session date and attendance. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “If ordered values tie and no stable secondary key exists, row_number, lag and frame-sensitive results may vary.” Apply this procedure: Add a unique tie-breaker or accept and document peer-level nondeterminism. The expected mechanism is: attempt_id turns equal scores into a stable total order. For the CCA attendance, add one near-miss that exposes calling a result deterministic because one test run looked stable. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: weather observations. Explain the rule using station, timestamp, temperature and rainfall. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “If ordered values tie and no stable secondary key exists, row_number, lag and frame-sensitive results may vary.” Apply this procedure: Add a unique tie-breaker or accept and document peer-level nondeterminism. The expected mechanism is: attempt_id turns equal scores into a stable total order. For the weather observations, add one near-miss that exposes calling a result deterministic because one test run looked stable. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: revision evidence. Transfer the rule using topic, attempt date, confidence and result. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “If ordered values tie and no stable secondary key exists, row_number, lag and frame-sensitive results may vary.” Apply this procedure: Add a unique tie-breaker or accept and document peer-level nondeterminism. The expected mechanism is: attempt_id turns equal scores into a stable total order. For the revision evidence, add one near-miss that exposes calling a result deterministic because one test run looked stable. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: budget ledger. Predict the rule using category, transaction date, amount and account. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “If ordered values tie and no stable secondary key exists, row_number, lag and frame-sensitive results may vary.” Apply this procedure: Add a unique tie-breaker or accept and document peer-level nondeterminism. The expected mechanism is: attempt_id turns equal scores into a stable total order. For the budget ledger, add one near-miss that exposes calling a result deterministic because one test run looked stable. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers calling a result deterministic because one test run looked stable.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Add a unique tie-breaker or accept and document peer-level nondeterminism.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny transport log with route, stop, time and passenger count. Include one ordinary case, one boundary and one deliberate failure caused by calling a result deterministic because one test run looked stable. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: If ordered values tie and no stable secondary key exists, row_number, lag and frame-sensitive results may vary. It shows a trace, not only a final value. The ordinary case should demonstrate “attempt_id turns equal scores into a stable total order.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Add a unique tie-breaker or accept and document peer-level nondeterminism. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
Window totals and averages support share-of-total and difference-from-group calculations without losing the source row. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is dividing integers or including the wrong population in the denominator. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Define units, numeric type, partition and excluded rows before calculation.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
100.0*amount/sum(amount) OVER (PARTITION BY month)Explained result. Each row reports its percentage of the declared monthly total. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: revision evidence. Explain the rule using topic, attempt date, confidence and result. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Window totals and averages support share-of-total and difference-from-group calculations without losing the source row.” Apply this procedure: Define units, numeric type, partition and excluded rows before calculation. The expected mechanism is: Each row reports its percentage of the declared monthly total. For the revision evidence, add one near-miss that exposes dividing integers or including the wrong population in the denominator. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: budget ledger. Transfer the rule using category, transaction date, amount and account. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Window totals and averages support share-of-total and difference-from-group calculations without losing the source row.” Apply this procedure: Define units, numeric type, partition and excluded rows before calculation. The expected mechanism is: Each row reports its percentage of the declared monthly total. For the budget ledger, add one near-miss that exposes dividing integers or including the wrong population in the denominator. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: transport log. Predict the rule using route, stop, time and passenger count. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Window totals and averages support share-of-total and difference-from-group calculations without losing the source row.” Apply this procedure: Define units, numeric type, partition and excluded rows before calculation. The expected mechanism is: Each row reports its percentage of the declared monthly total. For the transport log, add one near-miss that exposes dividing integers or including the wrong population in the denominator. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: project board. Contrast the rule using team, task, update time and status. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Window totals and averages support share-of-total and difference-from-group calculations without losing the source row.” Apply this procedure: Define units, numeric type, partition and excluded rows before calculation. The expected mechanism is: Each row reports its percentage of the declared monthly total. For the project board, add one near-miss that exposes dividing integers or including the wrong population in the denominator. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers dividing integers or including the wrong population in the denominator.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Define units, numeric type, partition and excluded rows before calculation.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny project board with team, task, update time and status. Include one ordinary case, one boundary and one deliberate failure caused by dividing integers or including the wrong population in the denominator. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: Window totals and averages support share-of-total and difference-from-group calculations without losing the source row. It shows a trace, not only a final value. The ordinary case should demonstrate “Each row reports its percentage of the declared monthly total.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Define units, numeric type, partition and excluded rows before calculation. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
Window queries often require sorting and can be expensive; indexes may help input access but do not erase every window sort. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.
The high-value mistake in this chapter is adding an index from a slogan without inspecting the actual plan. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Use EXPLAIN on representative data and test results with ties, NULLs and boundary frames.
Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.
Core worked example
EXPLAIN (ANALYZE,BUFFERS) SELECT ...Explained result. The observed plan and verified result set guide optimisation without changing semantics. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.
Four purposeful transfer cases
Case 1: transport log. Transfer the rule using route, stop, time and passenger count. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Window queries often require sorting and can be expensive; indexes may help input access but do not erase every window sort.” Apply this procedure: Use EXPLAIN on representative data and test results with ties, NULLs and boundary frames. The expected mechanism is: The observed plan and verified result set guide optimisation without changing semantics. For the transport log, add one near-miss that exposes adding an index from a slogan without inspecting the actual plan. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 2: project board. Predict the rule using team, task, update time and status. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Window queries often require sorting and can be expensive; indexes may help input access but do not erase every window sort.” Apply this procedure: Use EXPLAIN on representative data and test results with ties, NULLs and boundary frames. The expected mechanism is: The observed plan and verified result set guide optimisation without changing semantics. For the project board, add one near-miss that exposes adding an index from a slogan without inspecting the actual plan. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 3: test results. Contrast the rule using student, subject, score and sitting date. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Window queries often require sorting and can be expensive; indexes may help input access but do not erase every window sort.” Apply this procedure: Use EXPLAIN on representative data and test results with ties, NULLs and boundary frames. The expected mechanism is: The observed plan and verified result set guide optimisation without changing semantics. For the test results, add one near-miss that exposes adding an index from a slogan without inspecting the actual plan. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Case 4: reading progress. Stress-test the rule using reader, book, date and pages completed. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.
Reasoned route. Begin with “Window queries often require sorting and can be expensive; indexes may help input access but do not erase every window sort.” Apply this procedure: Use EXPLAIN on representative data and test results with ties, NULLs and boundary frames. The expected mechanism is: The observed plan and verified result set guide optimisation without changing semantics. For the reading progress, add one near-miss that exposes adding an index from a slogan without inspecting the actual plan. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.
Diagnostic route
- Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
- Boundary check: create the smallest input that triggers adding an index from a slogan without inspecting the actual plan.
- Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
- Repair check: use the reversible procedure “Use EXPLAIN on representative data and test results with ties, NULLs and boundary frames.” and record the first changed observation.
- Transfer check: repeat the rule in a second context and identify what remains invariant.
A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.
Practice with an explained answer
Question. Build a tiny test results with student, subject, score and sitting date. Include one ordinary case, one boundary and one deliberate failure caused by adding an index from a slogan without inspecting the actual plan. Predict each result before using a tool, then report the first point where observation differs from prediction.
Answer guide. A strong response starts with the rule: Window queries often require sorting and can be expensive; indexes may help input access but do not erase every window sort. It shows a trace, not only a final value. The ordinary case should demonstrate “The observed plan and verified result set guide optimisation without changing semantics.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Use EXPLAIN on representative data and test results with ties, NULLs and boundary frames. Other data choices are valid when the evidence supports the same causal chain.
Decision and transfer
Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.
Previous chapter . Contents . Next chapter
Parent guide: choose the next useful step
Start with evidence, not a label such as careless. Ask for one prediction and one trace. If the first transition is wrong, rebuild the model. If the model is sound but syntax fails, practise reference use. If routine cases are correct but boundaries fail, vary ties, defaults, unsupported inputs, ownership or missing paths. If explanations transfer, move to a small project.
Keep a weekly record with four lines: concept, prediction, observed difference and next test. Stop when fatigue replaces reasoning. A smaller case tomorrow is more useful than another hour of copying tonight.
Seek specialist help when cause and effect remain invisible after examples are reduced, when accessibility or data-loss implications are unclear, or when an important repository, database or application state may be at risk. Good support should make the learner’s reasoning more independent.
Capstone practice with explained routes
1. test results: model, boundary and recovery
Create a small test results using student, subject, score and sitting date. Combine “Rows remain rows” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.
Explained route. Start with: Window functions add calculations to a row set without collapsing rows the way grouped aggregation does. Apply: Write the desired output grain before selecting aggregation or a window. Verify: Every result row remains, with the overall average repeated as context. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.
2. reading progress: model, boundary and recovery
Create a small reading progress using reader, book, date and pages completed. Combine “Window ORDER BY versus result ORDER BY” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.
Explained route. Start with: ORDER BY inside OVER controls the analytic sequence; the query’s final ORDER BY controls displayed row order. Apply: Specify both when both meanings matter and compare their roles. Verify: Numbers follow descending scores, but the final SELECT still needs ORDER BY for guaranteed display order. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.
3. CCA attendance: model, boundary and recovery
Create a small CCA attendance using activity, participant, session date and attendance. Combine “Running totals need order and frame” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.
Explained route. Start with: An ordered aggregate window can produce a cumulative result, but the exact included rows depend on its frame. Apply: State the frame explicitly when duplicate order values matter. Verify: Each row includes itself and all earlier rows in the declared order. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.
4. weather observations: model, boundary and recovery
Create a small weather observations using station, timestamp, temperature and rainfall. Combine “LAG reads an earlier row” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.
Explained route. Start with: LAG returns a value from a preceding row in the window order, with optional offset and default. Apply: Partition by entity and order by a stable timestamp plus key. Verify: Each attempt can be compared with the student’s preceding ordered attempt. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.
5. revision evidence: model, boundary and recovery
Create a small revision evidence using topic, attempt date, confidence and result. Combine “Aggregates become window functions” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.
Explained route. Start with: Ordinary aggregates such as sum, avg, min and max act as window functions when followed by OVER. Apply: Keep the detailed FROM/WHERE row set and add window context deliberately. Verify: Each transaction can express its share of the category total. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.
6. budget ledger: model, boundary and recovery
Create a small budget ledger using category, transaction date, amount and account. Combine “Filtering window results needs a later query stage” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.
Explained route. Start with: In PostgreSQL, window functions run after WHERE and GROUP BY, so filtering their results requires a subquery or CTE. Apply: Calculate in an inner query, then filter the named result outside. Verify: The outer query can filter the already-computed window value. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.
7. transport log: model, boundary and recovery
Create a small transport log using route, stop, time and passenger count. Combine “Percentages and cohort comparisons” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.
Explained route. Start with: Window totals and averages support share-of-total and difference-from-group calculations without losing the source row. Apply: Define units, numeric type, partition and excluded rows before calculation. Verify: Each row reports its percentage of the declared monthly total. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.
8. project board: model, boundary and recovery
Create a small project board using team, task, update time and status. Combine “Reading the OVER clause” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.
Explained route. Start with: OVER defines the row context for a window call; empty parentheses mean all rows in the virtual table. Apply: Underline function, partition, order and frame as separate clauses. Verify: The total is calculated over every row visible to the query stage. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.
Frequently asked questions
How long should a practice session be?
Use one complete prediction–observation–explanation cycle while attention remains good. Ten to twenty focused minutes can be enough.
Should every option or function be memorised?
No. Memorise the governing distinctions and practise retrieving the official reference. Understanding means predicting and explaining, not reciting a parameter list.
What if the result is correct but the explanation is weak?
Treat it as partial success. Ask for a trace and change one boundary. A reliable model survives controlled variation.
Is the shortest solution the best?
Not automatically. Prefer the solution whose semantics, failure modes and maintenance cost are easiest to justify for the actual project.
When should official documentation be used?
Use it whenever syntax, supported types, SQL dialect behaviour or Git version details matter. Primary documentation settles the current contract.
How can a parent help without technical expertise?
Ask what was predicted, where the first difference appeared, what evidence matters and which smaller example could isolate it.
How do we test transfer?
Change the context, vocabulary and one boundary. Require the learner to identify the invariant before using a tool.
What should be saved after practice?
Keep the corrected rule, one trace, one boundary case and the next question. Avoid storing pages of unexplained output.
Can these exercises replace backups?
No. Use disposable examples and proper backups. Learning should not endanger schoolwork, repositories or personal data.
What counts as mastery?
The learner can predict, verify, diagnose, recover and justify a choice across more than one context, while knowing when to consult the current reference.

