Data Transformation and Processing Logic Questions
Implementing transformation logic: joins, aggregations, deduplication, pivoting/reshaping, and business-rule application over datasets. Covers writing correct and maintainable transformation code, handling edge cases in the transform layer, and preparing data for downstream consumption. Focuses on the logic of turning raw data into analytics-ready outputs.
Implement a discount or promotion rule as deterministic, testable logic: for example, a line item qualifies for a discount only when several conditions all hold (a flag on the customer, a threshold on the order total, and a lookback window with no qualifying event). When multiple promotions could apply to the same item, the best discount should win. Provide an implementation (SQL or pseudocode) and describe how you would unit-test the rule set, including its edge cases.
Sample Answer
Direct answer
Express each condition of a business rule as its own explicit boolean, combine them with AND/OR exactly as the business states the rule (not as a simplified approximation), and when multiple rules can apply to the same record, compute every rule's outcome and take the best one explicitly (e.g. GREATEST(...)), rather than relying on evaluation order to pick a "first match."
Structured elaboration
- One CASE/boolean expression per rule: each business condition (a flag, a threshold, a lookback window) becomes its own named boolean, both for readability and because each one is independently unit-testable.
- "Best wins" as an explicit aggregate, not an if/elif chain: an if/elif chain silently depends on the order the rules happen to be written in; computing every applicable discount and taking the maximum is both more readable and immune to someone reordering the rules later and silently changing the outcome.
- Testability: because each rule is its own boolean condition, you can unit test it in isolation (does the 30-day lookback correctly exclude a customer who returned something 29 days ago? 31 days ago?) rather than only testing the rule set as an opaque whole.
- Determinism: the whole point of expressing this as data-driven boolean logic rather than procedural code with early returns is that the same input always produces the same output, regardless of which order operations happen to execute in.
Worked example
SELECT item_id,
GREATEST(
CASE WHEN user_is_premium AND order_total > 100 AND days_since_last_return >= 30 THEN 0.10 ELSE 0 END,
CASE WHEN order_total > 120 THEN 0.05 ELSE 0 END
) AS discount
FROM line_items;
Verified against three items: item 1 (premium, total 150, 40 days since return) qualifies for the 10% premium rule, which beats the 5% volume rule, so it gets 0.10. Item 2 (premium, total 150, only 5 days since return) fails the 30-day lookback on the premium rule, so it falls back to the 5% volume rule (0.05). Item 3 (not premium, total 150) never qualifies for the premium rule at all, and also gets 0.05 from the volume rule. The GREATEST pattern correctly picks the best applicable discount in every case without depending on rule-evaluation order.
Trade-offs and pitfalls
GREATEST(or an equivalent aggregate-of-all-rules approach) does more computation than a short-circuiting if/elif, evaluating every rule for every row; for a small number of rules per row this cost is negligible, for hundreds of rules at high throughput it becomes a real design constraint worth naming (see the related rules-engine-design question for that scale).- Boolean conditions built from business language ("has not returned any order in the previous 30 days") need a precise, tested definition of the boundary (is exactly 30 days included or excluded?); get this wrong and the bug only shows up on specific dates, making it hard to reproduce.
- Unit tests for a rule set like this should specifically include the boundary cases (exactly at a threshold, exactly at the lookback cutoff), since those are where an off-by-one in a
>versus>=actually surfaces.
A dataset has missing values scattered across several columns. Walk through how you would decide what to do about each column's missingness, and how you would document and communicate that decision to stakeholders who will consume the resulting dashboard or model.
Sample Answer
Direct answer
The right way to handle a column's missing values depends first on WHY the data is missing, not just on how much is missing; understanding whether the missingness is completely random (MCAR), related to observed data (MAR), or related to the missing value itself (MNAR) should drive the choice between dropping, imputing, or explicitly flagging missingness as its own category.
Structured elaboration
- MCAR (missing completely at random): the fact that a value is missing has nothing to do with any variable, observed or not. Dropping rows is relatively safe here since it doesn't systematically bias the remaining data, though it still costs sample size.
- MAR (missing at random, conditional on observed data): missingness correlates with something you CAN observe (e.g. income is more often missing for self-employed respondents, and you know who's self-employed). Imputation conditioned on the observed correlate (model-based, or at least stratified by the correlate) is more defensible than a single global mean/median.
- MNAR (missing not at random): the missingness itself depends on the unobserved value (e.g. very high earners are more likely to decline to state income). This is the hardest case, naive imputation can systematically bias results, and an explicit "missing" indicator/category, or a domain-informed model of the missingness mechanism itself, is often more honest than pretending you can fill it in accurately.
- When to add an indicator instead of imputing a value at all: if the fact that a value is missing is itself informative (which is common under MAR/MNAR), an explicit missing-indicator feature can carry real signal that a filled-in value would erase.
- Communicating the choice: document which strategy was used per column and why, since a stakeholder consuming a dashboard or a model built on imputed data needs to know how much of what they're looking at is real versus filled-in, especially for columns with high missingness rates.
Worked example
A churn dataset with missing values in income, last_login, and plan_type, where the missingness patterns differ:
plan_typemissing only for very old accounts predating a schema migration: this looks close to MCAR (the migration is unrelated to any account's actual behavior), dropping or imputing with the overall mode is comparatively low-risk.last_loginmissing specifically for accounts that never logged in after signup: this is closer to MNAR-adjacent (the missingness IS the signal, "never logged in"), so an explicit "never logged in" category, not any numeric imputation, is the appropriate handling.incomemissing more often among certain segments who chose not to disclose it: closer to MAR/MNAR, a global mean/median fill would understate the real variation and should be flagged to stakeholders as a known limitation, or handled with a segment-conditioned estimate instead.
Trade-offs and pitfalls
- Defaulting to "just impute with the mean/median" for every column regardless of the missingness mechanism is the most common mistake; it's the easy answer but not always the correct one.
- An explicit missing-indicator column can leak information in a modeling context if the indicator itself was constructed using information not actually available at prediction time; treat it with the same point-in-time discipline as any other feature.
- Communicating "this metric is based on N% imputed values" honestly changes how much a stakeholder should trust a headline number, saying so is uncomfortable but is exactly the trust-preserving move a senior analyst makes.
A numeric column contains both NULLs and extreme outliers. Describe a pragmatic decision process for handling both before analytics: statistical detection methods (IQR, z-score), business-rule thresholds, when to impute versus flag versus drop, and how you would document and test these decisions so downstream analysts understand what happened to their data.
Sample Answer
Direct answer
Handling nulls and outliers in the same numeric column requires two separate decision processes run side by side, not one: for nulls, decide impute versus drop versus flag based on the missingness mechanism; for outliers, decide flag versus drop versus cap based on statistical detection (IQR or z-score) combined with a business-rule sanity check, and document both decisions so downstream analysts know what happened to their data.
Structured elaboration
- Statistical outlier detection: IQR-based bounds (values beyond 1.5x the interquartile range from the quartiles) are robust to the outliers themselves distorting the detection; a z-score/standard-deviation-based bound is simpler to compute but can miss outliers when several occur together (the outliers inflate the standard deviation used to judge them).
- Business-rule thresholds as a complement, not a replacement: a purely statistical bound doesn't know that a negative age or a transaction of $10 million is implausible on its face; domain-specific hard bounds catch cases that a purely distributional method might not flag as statistically unusual in a small or skewed sample.
- Impute vs. flag vs. drop, for BOTH nulls and outliers: dropping is simplest but costs sample size and can bias results if the dropped values aren't random; flagging (keeping the value but marking it) preserves information for downstream review; imputing/capping substitutes a value, which is only defensible when you can state what you're substituting and why.
- Documentation and testing: whatever the decision, document it per column (which threshold, which strategy) and add tests so a later pipeline change doesn't silently alter the assumptions a report or model was built on.
Worked example
A revenue column with a few NULLs and a few outlier values: apply the null-handling decision (say, MAR-informed imputation, or an explicit "missing" flag) first, since an outlier check computed over data that still contains unhandled nulls can behave unpredictably depending on how the engine treats NULL in an IQR or standard-deviation calculation. Then apply outlier detection (IQR is the more robust default given the earlier finding that a small number of co-occurring outliers can inflate a standard-deviation-based threshold enough to mask themselves) to the now-null-free column, deciding per business context whether a flagged outlier should be capped, excluded from an aggregate, or kept with a visible flag for a human to review.
Trade-offs and pitfalls
- Running outlier detection BEFORE resolving nulls (rather than after) can produce a statistic (mean, standard deviation, quartile boundaries) computed inconsistently depending on how NULLs happen to be handled by the specific function used, do the null-handling step first.
- A z-score threshold alone can silently miss multiple co-occurring outliers precisely because they inflate the very standard deviation the threshold is based on (a concrete, verified instance of this masking effect is worked out in the window-function outlier-flagging answer); prefer IQR, or at minimum sanity-check a z-score-based result against a robust alternative.
- Capping an outlier to a boundary value (winsorizing) changes the shape of the distribution in a way a simple flag does not; state which one you did, since they have different downstream statistical implications.
Multiple data sources represent the same categorical attribute with different spellings or abbreviations (for example 'NY', 'New York', 'new_york', 'NYC' all meaning the same state or city). Describe a practical pipeline to detect, normalize, and maintain a mapping for these variants before merging datasets, including fuzzy matching, a maintained ruleset, and a human-in-the-loop step for ambiguous cases.
Sample Answer
Direct answer
Maintain an explicit, versioned mapping from every known variant spelling to one canonical category value, apply it during ingestion or transformation, and route anything that doesn't match a known variant to human review rather than guessing a mapping automatically, since a wrong automatic guess here silently corrupts every downstream aggregation grouped by that category.
Structured elaboration
- Normalize before matching: lowercase, strip punctuation, and collapse separators (underscores, hyphens) to a consistent form before comparing against the known-variants map, so trivial formatting differences don't require their own separate map entries.
- Explicit mapping, not fuzzy matching, as the default: for a bounded, known set of categories (states, a fixed product taxonomy), an explicit dictionary of known variants to canonical values is more predictable and auditable than a similarity-based fuzzy match, reserve fuzzy matching for genuinely open-ended text.
- Unrecognized values return None/unmapped, not a guess: a value that doesn't match anything in the known-variants map should be surfaced for human review and addition to the map, not silently passed through unmapped or silently mapped to the closest-looking known value.
- Maintaining the mapping over time: this map needs to be a living, versioned artifact (not a one-time script), since new source systems will periodically introduce new spelling variants that need to be added.
Worked example
CANON_MAP = {'ny':'New York', 'new york':'New York', 'new_york':'New York', 'nyc':'New York'}
def normalize_category(raw):
key = raw.strip().lower().replace('_',' ').replace('-',' ')
return CANON_MAP.get(key.replace(' ',''), CANON_MAP.get(key, None))
Verified: 'NY', 'new_york', and 'NYC' all correctly map to 'New York'; 'Chicago', which has no entry in the known-variants map, correctly returns None rather than being silently mis-mapped, signaling that it needs either its own mapping entry or human review to confirm it's genuinely a different category.
Trade-offs and pitfalls
- A mapping table that's built once and never revisited will slowly accumulate "unmapped" values as new sources are onboarded; treat unmapped-value counts as an operational metric to monitor, not a one-time cleanup task.
- Being too aggressive with normalization (stripping too much punctuation, treating too many things as equivalent) can accidentally merge two genuinely distinct categories that happen to normalize to the same key; validate the mapping against a domain expert, not just against the raw data's own patterns.
- This differs from the earlier fuzzy-entity-resolution competency in an important way: that one handles genuinely open-ended, unbounded text (people's names) where similarity scoring is the only practical tool; this handles a small, bounded, enumerable set of known categories, where an explicit map is both more accurate and more auditable than a similarity score would be.
Given a users table and a transactions table, write a SQL query using window functions to build a per-user feature/summary table in one pass: last transaction date, a rolling count of transactions in the past 30 days, a rolling average amount over the past 90 days, and days since signup. Explain how you handle a user who has never transacted.
Sample Answer
Direct answer
Compute several related per-entity metrics (a most-recent-date, a rolling count, a rolling average, a tenure calculation) in one query using window functions and conditional aggregates keyed on the same partition, rather than writing four separate queries and joining their results back together; the main correctness requirement is that entities with NO matching activity still appear in the output with well-defined (NULL or zero) values rather than being silently dropped.
Structured elaboration
- One partition, several window functions:
MAX(...) OVER (PARTITION BY user_id)for the most recent date,COUNT(...) FILTER (WHERE ...)for a windowed count, andAVG(...) FILTER (WHERE ...)for a windowed average can all be computed together against the same joined result, each with its own time-window filter condition. - Users with zero matching transactions: a LEFT JOIN from the entity table to the transaction table, rather than an INNER JOIN, ensures a user with no transactions at all still produces one output row, with NULL (not a dropped row) for every transaction-derived metric.
- Tenure calculation:
days_since_signupis computed directly from the entity's own signup date against a reference date, independent of whether they have any transactions, so this column is always populated even when the transaction-derived ones are NULL.
Worked example
SELECT u.id,
MAX(t.occurred_at) AS last_transaction_date,
COUNT(t.id) FILTER (WHERE t.occurred_at >= DATE '2024-01-01' - INTERVAL 30 DAY) AS txn_30d,
AVG(t.amount) FILTER (WHERE t.occurred_at >= DATE '2024-01-01' - INTERVAL 90 DAY) AS avg_amt_90d,
DATE_DIFF('day', u.signup_date, DATE '2024-01-15') AS days_since_signup
FROM tusers u LEFT JOIN ttx t ON u.id = t.user_id
GROUP BY u.id, u.signup_date;
Verified against two users, one with two transactions and one with none: the user with transactions correctly gets a populated last_transaction_date, a 30-day count, and a 90-day average, while the user with zero transactions correctly appears in the result with NULL for every transaction-derived metric (not dropped from the output) and a correctly-computed days_since_signup regardless.
Trade-offs and pitfalls
- Using an INNER JOIN instead of a LEFT JOIN here silently excludes every zero-activity entity from the output entirely, which is a common and easy-to-miss mistake since the query still "runs successfully" and looks plausible.
- Multiple
FILTER (WHERE ...)clauses against the same joined rows are cleaner and less error-prone than multiple separately-joined subqueries computing the same metrics, but not every SQL dialect supportsFILTER; the equivalentSUM(CASE WHEN ... THEN ... ELSE 0 END)/AVG(CASE WHEN ... THEN ... END)pattern works everywhereFILTERdoesn't. - Computing several time-windowed metrics (30-day, 90-day) against the SAME joined rows means the join itself isn't filtered by any of those windows, only the individual metric expressions are, get this backward (filtering the join itself to the smallest window) and the larger windows silently lose data.
Unlock Full Question Bank
Get access to all 25 Data Transformation and Processing Logic interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.