PeaBox Lab › PeaLang › Learn › Chapter 16 › Lesson 3

Part III — Advanced Systems · Chapter 16 · Lesson 3 of 6 · 11 min read

Lesson 3: Select, Filter, Calculated Columns, Drop, Rename, Sort, Limit, and Distinct

Lesson level: Advanced

Purpose: Build understandable table transformations whose schemas, row populations, and ordering can be tested independently.

Learning objectives

By the end of this lesson, you should be able to distinguish column selection from row filtering; define calculated fields; remove and rename columns without breaking downstream contracts; sort deterministically; apply limits for the correct purpose; and distinguish duplicate records from repeated business keys.

Example convention. Transformation recipes are conceptual specifications, not executable method signatures. The chapter’s earlier illustrative data API must be checked against the installed runtime before implementing a recipe.

3.1 Read a transformation as a contract

Every operation has an input contract and an output contract. Describe the input schema, output schema, row-grain effect, ordering effect, null policy, and failure conditions. This makes a long pipeline easier to review than a chain of unexplained calls.

An order-detail report might retain order_id, region, and amount; keep only approved orders; derive a value band; sort by region and order_id; and expose a limited preview. Those operations answer different questions. Projection changes available fields. Filtering changes population. Derivation adds meaning. Sorting changes sequence. A preview limit does not define the analytical population.

Choose names that distinguish stages: normalized_orders, approved_orders, classified_orders, and report_rows. Do not reuse one variable name when that hides a changing grain or population.

Guided practice

For each operation in the proposed report, state which properties change and which remain invariant. Identify the earliest point at which amount may be dropped. Explain why dropping it before classification would break a dependency.

Common mistake: treating a compact method chain as self-documenting. A short expression can still hide a population change or a key loss.

3.2 Select, drop, and rename: control the column contract

Select keeps an explicit set of fields. It is useful for a stable downstream interface because new source columns do not automatically appear in the output. Drop removes named fields and keeps the others. It is convenient internally, but newly added input fields may survive unless an explicit output check prevents them.

Rename changes a field’s public name without intentionally changing its values. It must not create a collision. Renaming amount to gross_amount can improve meaning; renaming it to net_amount without changing the calculation misrepresents the data.

Keep keys and audit references until the pipeline no longer needs them. A report that selects only region and amount may be sufficient for presentation but insufficient for tracing a suspicious row back to its order. Maintain a controlled detailed result separately if the consumer should not see identifiers.

Illustrative recipe: input contains order_id, customer_id, region, amount, status, and internal_note. Output selects order_id, region, amount, and status; renames amount to gross_amount; rejects a collision with an existing gross_amount field. The recipe does not authorize disclosure of the internal note.

Review downstream expressions after renaming. Their dependencies must refer to the new name. A transformation ledger helps: each row lists stage, available fields, renamed fields, and fields required by later work.

Guided practice

Design a customer-facing report that excludes internal_note and customer_id but preserves the fields needed for its calculations. Decide whether an explicit select or a drop is safer when the input schema may gain confidential fields.

Common mistakes. Dropping a key too early breaks joins and reconciliation. Renaming for appearance can obscure units. Selecting duplicate output names creates an ambiguous contract. Assuming metadata survives every transformation requires evidence from the implementation.

Review prompt: Why is an explicit output field allowlist usually safer than a denylist when source schemas evolve?

3.3 Filter: define the analytical population

A filter retains rows according to a predicate. Its business meaning is the population definition: which orders qualify for this report? Write that definition in plain language before translating it into an expression. A syntactically correct predicate can still select the wrong population.

Suppose the report covers approved orders from the north region with known positive amounts. The contract requires approval, the specified region, a known amount, and a positive value. Unknown amounts should be handled deliberately, not left to an assumed table-level truthiness rule.

Illustrative predicate: status equals approved AND region equals north AND amount is known AND amount is positive. This is conceptual notation. Confirm the actual expression builder, null predicate, and evaluation behavior in the installed data engine.

Scalar language short-circuit rules do not automatically describe a column-expression engine. An engine may evaluate column expressions differently, especially when expressions are deferred. If division or parsing can fail, use a verified safe operation or validate the input before applying the calculation; do not assume that one conjunct always protects another.

Keep exclusions visible. A row may be valid source data but outside this report’s population. That is different from rejection for malformed data. Record exclusion reasons separately so quality defects are not confused with legitimate reporting boundaries.

Annotated example. A cancelled order with a valid amount is excluded by status. An approved order with malformed amount text belongs in validation rejects. An approved zero-value order is valid but excluded by the positive-amount report rule.

Guided practice. Prepare a predicate decision table for approved, cancelled, unknown-status, positive, zero, negative, and missing-amount cases. State the expected retain, exclude, or reject outcome.

Common mistake: filtering away invalid values without a quality record can make a damaged source look healthy. Decide whether invalid inputs must fail or be quarantined before selecting the report population.

Review prompt: How would filtering cancelled orders before computing a cancellation rate invalidate the metric’s denominator?

3.4 Calculated columns: make derivation explicit

A calculated column derives a value for each row. Its contract should specify the source fields, formula, output name, representation, units, null behavior, and invalid-input policy. Adding a field should not silently change the table’s grain.

Distinguish a row calculation from an aggregate. Deriving line_value from quantity and unit_value applies within each order line. Computing total sales for a region combines multiple rows and belongs to grouped aggregation. The names and output shape should communicate that difference.

Illustrative derivation: line_value = quantity multiplied by unit_value. If either required input is missing, reject the row or retain an explicitly unknown result according to the contract. If the output represents money, select an exact supported representation or a verified host-side calculation policy; do not infer decimal support from the chapter’s illustrative type names.

When calculations depend on other derived fields, make the order explicit. Define gross_value before discount_value, and define net_value only after both are available. Do not assume that fields introduced together in one operation can refer to each other unless the engine documents that behavior.

Conditional columns also require complete outcomes. A hypothetical value_band may be small below a named threshold and large at or above it. The exact boundary must be tested. An unknown value needs a separate result rather than accidental placement in the smaller band.

Keep pure derivations free of unrelated side effects. A row transformation should not send messages, write files, or retrieve remote policy values for every record. Resolve approved reference data before the transformation where practical, and test the calculation independently.

Guided practice. Define a calculated field register for gross_value, discount_value, net_value, and value_band. List dependencies, units, failure rules, and boundary cases. Explain which definitions can be evaluated independently.

Common mistakes. Overwriting amount erases provenance. Mixing currencies creates an invalid total. Rounding at an undocumented intermediate step changes results. Returning text in one branch and a number in another creates an unclear output contract.

Review prompt: Why should a calculation’s null policy be specified separately from its formula?

3.5 Sort and limit: ordering is part of the result

Sorting establishes a row sequence. A sort specification needs field names, ascending or descending direction, null placement, and a tie-breaking rule where repeatable output matters. Without a defined order, the first rows are not necessarily the most recent, largest, or most important rows.

For a detail report, sorting by ordered_at alone leaves ties unresolved. Add order_id as a secondary key when it uniquely identifies the remaining records. If neither field combination is unique, define another stable tie-breaker or accept that tied order is unspecified.

Illustrative recipe: sort valid orders by ordered_at descending, then order_id ascending; place missing timestamps in a documented position or reject them beforehand; retain the first requested number of records for a preview. Confirm all ordering options against the actual engine.

A limit restricts output size. Applied after sorting, it can express a top-result contract. Applied before sorting, it sorts only the retained subset and can miss qualifying records elsewhere in the input. Applied before aggregation, it changes the population being summarized.

Separate three uses of a limit: a human preview, a business-defined top-result query, and a protective processing bound. A preview should not feed a full-population metric. A protective bound should fail visibly when complete processing is required rather than silently discard the excess.

Sorting can also change resource requirements. A full order may require retaining substantial data before any result is returned. A small output does not prove a small intermediate workload. Establish budgets for the complete operation, not just the displayed rows.

Guided practice. Compare these conceptual sequences: limit then sort, sort then limit, and group then sort then limit. Describe the question each answers and identify which can produce a misleading sales summary.

Common mistakes. A nondeterministic tie order creates flaky tests. Text sorting of numeric representations gives unexpected ordering. Missing timestamps can appear in a surprising position. Displaying a small preview can conceal that the pipeline evaluated a much larger input.

Review prompt: Why should a report’s sort order and tie policy be included in its acceptance criteria?

3.6 Distinct: equality is not identity

Distinct retains unique records or unique combinations of specified fields. Before using it, define what duplicates mean. Two rows can share a customer identifier because the customer placed different orders. Those rows are not duplicate orders.

Whole-row distinct removes repeated representations. Key-based deduplication requires a stronger rule: which row represents the authoritative record when the same business key appears more than once? A convenient first-row choice is not automatically correct.

Separate exact duplicates, conflicting duplicates, and legitimate repeated keys. Exact duplicates may arise from a replayed file. Conflicting duplicates may describe corrections or a source defect. Repeated customer_id values may be expected in an order table whose key is order_id.

Illustrative case. Two records share order_id but differ in status and update timestamp. The pipeline must either apply an approved latest-version rule or reject the conflict. Whole-row distinct keeps both; arbitrary key-based distinct may discard the valid correction.

If a latest-version rule is approved, define the timestamp source, ordering direction, tie behavior, and treatment of missing update times. Equal timestamps with conflicting values require a conflict policy. Do not assume stable input order resolves business authority.

Preserve evidence of removal. A deduplication report should identify the key rule, duplicate category, selected version, and discarded-record references. Keep sensitive values out of ordinary logs while retaining enough controlled evidence to reproduce the decision.

Distinct can require memory proportional to observed uniqueness. A table with many unique keys behaves differently from a table dominated by repetition. Test resource use with the distribution relevant to the application rather than only a small repeated fixture.

Guided practice. Classify a replayed order, two different orders from one customer, and two conflicting versions of one order. State the correct action and the grain of the resulting table.

Common mistake: applying distinct to a small subset of columns can merge separate entities that happen to share those values. Keep the business key until the intended aggregation or projection makes its removal safe.

Review prompt: Why is removing exact duplicate rows different from selecting the authoritative version of a business record?

3.7 Hands-on lab: A deterministic detail report

Scenario. Build a hypothetical approved-order report using the normalized interchange fixtures. Use verified DataFrame operations where available and a clearly identified adapter elsewhere. Do not copy conceptual recipes into executable source without resolving their method signatures.

Required stages. Retain the business keys and calculation fields. Separate validation rejects from reporting exclusions. Derive a clearly named value band. Rename the public amount field accurately. Produce a deterministic order and a separate limited preview. Apply an explicit duplicate policy.

Test fixture. Include a valid approved order, a cancelled order, a zero-value order, a missing amount, an exact duplicate, conflicting versions of one key, equal timestamps, and an internal note that must not appear publicly. Choose synthetic values and record expected outcomes before execution.

Evidence. At every stage, record the available fields, retained keys, grain, exclusions, and ordering rule. A row-count change needs an explanation. A renamed or removed field needs a dependency check. The full result must remain distinct from its preview.

Acceptance criteria. The final output contains only approved public fields; retains the intended population; has the declared derived-field meaning; resolves or rejects duplicates according to policy; and repeats deterministically for unchanged inputs. Missing or invalid values are not silently repaired.

Diagnostic exercise. Introduce an early limit before filtering, then compare the resulting population with the correct sequence. Restore the correct order. Next remove a required calculation field and verify that the dependency failure is detected visibly.

Review questions. How does select differ from drop? Which operation changes population? Why must a calculated field declare units? What makes sorting deterministic? When does a limit distort a metric? Why does whole-row distinct not resolve conflicting key versions?

Applied challenge. Make the detail transformation reusable for different approved regions without broadening its public output schema. Define parameters, input assumptions, output invariants, and failure cases. Explain which fields must remain internal.

Lesson summary. Projection, filtering, derivation, renaming, sorting, limiting, and distinct each change a different part of the table contract. Keep those effects explicit and test them independently.

Common mistakes

Review questions

Applied challenge

Take a raw orders table with duplicates, nulls and inconsistent column names. Write a transformation that standardizes names, removes test orders, adds a net-amount column, keeps the latest record per order, and returns the ten largest orders. Document each step and the row count after it.

Lesson summary

Column selection, filtering, calculated columns, sorting, limiting, and distinct are the building blocks of every tabular pipeline. Write them as small, named, explicit steps, filter early, sort before limit, treat nulls deliberately, and record row counts so each transformation can be verified.

Lesson status: Ready for review.

← Previous Next →