MICROSOFT POWER BI • DATA PREPARATION WITH POWER QUERY

Handling Missing Values — Handle missing values and errors (nulls, error rows) (intro)

Master the strategies for detecting and resolving nulls and error rows in Power Query before they corrupt your data models.

Historical Context & Motivation

The challenge of missing data is as old as data collection itself. When Edgar F. Codd introduced the relational model in 1970, he anticipated that real-world datasets would inevitably contain incomplete information, leading him to propose the concept of null as a marker for unknown or inapplicable values. This seemingly simple design decision sparked decades of theoretical debate—particularly around three-valued logic and the correct semantics for comparisons involving nulls—but it also established a fundamental truth: production data is never perfectly clean, and any serious data pipeline must account for gaps and inconsistencies.

As the field of business intelligence matured through the 1990s and 2000s, ETL (Extract, Transform, Load) processes became the standard for cleaning data before it reached analytical systems. Tools like SQL Server Integration Services (SSIS) offered programmatic ways to detect and handle missing values, but they required substantial developer expertise. Microsoft recognized that self-service BI needed a more accessible approach, and in 2013 Power Query was introduced as an add-in for Excel—later becoming the native data preparation engine in Power BI. Its graphical interface and functional M language democratized data cleansing, making null and error handling accessible to a far broader audience of analysts and engineers.

1970
Codd's Relational Model
Edgar F. Codd formalizes the relational model at IBM and introduces null as a first-class concept for representing missing or inapplicable data in tables.
1998
Rise of ETL Tooling
Enterprise ETL platforms (Informatica, DataStage, later SSIS) standardize data-cleansing pipelines, including systematic null detection, default-value substitution, and error-row redirection.
2013
Power Query for Excel
Microsoft releases Power Query as an Excel add-in, providing a GUI-driven data preparation layer with built-in null and error handling through the M functional language.
2015
Power BI Desktop Launch
Power BI Desktop ships with Power Query (now called "Power Query Editor") as its native data-ingestion engine, embedding null/error handling directly into BI report development workflows.
2023
Dataflows Gen2 & Fabric
Microsoft Fabric extends Power Query into cloud-scale dataflows, preserving the same null and error handling semantics while enabling enterprise-grade data lakehouse architectures.

The central question that Power Query's null and error handling addresses is deceptively straightforward: when a data value is absent or a transformation fails, what should the system do? Ignoring the problem leads to wrong aggregations, broken relationships, and misleading dashboards. The sections that follow introduce a systematic framework for detecting, classifying, and resolving these issues within the Power Query Editor.

Core Principles & Definitions

Before diving into Power Query's specific tools, it is important to establish a precise vocabulary. In Power Query's type system, there are two fundamentally different kinds of "bad" cells: nulls and errors. Though both represent data that cannot be used directly in analysis, they arise from distinct causes and demand different remediation strategies. Understanding this distinction is the single most important foundation for data cleansing in Power BI.

1

Null (Missing Value)

A null represents the intentional absence of a value. It is a valid M-language literal (null) and can appear in any column regardless of type. Nulls propagate through most arithmetic and text operations—e.g., null + 5 = null.
2

Error (Failed Computation)

An error occurs when Power Query cannot evaluate a cell's expression—e.g., dividing by zero, a type-conversion failure, or a missing key during a merge. Error cells display a red Error badge and carry a reason/message/detail record.
3

Error Row vs. Error Cell

A single error in one cell does not invalidate the entire row. Power Query evaluates each cell independently, so a row can contain a mix of valid values and errors. An error row is simply a row that has at least one error cell. The "Remove Errors" command removes the entire row if any cell is in error.
4

Null Propagation Semantics

Following SQL's three-valued logic tradition, most M operators treat null as "unknown." Arithmetic with null yields null; comparisons with null yield null (not true or false). Aggregations like List.Sum and List.Average silently skip null entries.
5

Defensive Transformation

The principle of writing transformations that anticipate and gracefully handle nulls and errors, using constructs like try...otherwise and if value = null then ... else .... This mirrors defensive programming practices you already apply in languages like Java or Python.
KEY TAKEAWAY
Think of nulls and errors as two categories in an exception-handling system you'd design in software engineering. A null is like a function returning Optional.empty() in Java—it's a valid, expected outcome indicating no data. An error is like an uncaught exception—something went wrong during computation. Just as you wouldn't catch a NullPointerException and a DivisionByZeroException with the same handler, you shouldn't treat nulls and errors identically in Power Query.

Visual Explanation — Null & Error Flow in Power Query

The diagram below models how data flows through Power Query's transformation pipeline when null and error values are present. Each row entering a query step can emerge in one of three states: valid (all cells have concrete values), null-bearing (one or more cells contain null), or error-bearing (one or more cells failed evaluation). Understanding this tri-state classification is essential for choosing the right remediation strategy.

Data entering a Power Query step can exit as valid (green), null-bearing (amber), or error-bearing (red). The lower panel shows the remediation strategies available for each category. Preventive strategies (purple) reduce the occurrence of both nulls and errors before they propagate.

Notice that the diagram separates the remediation strategies for nulls and errors into distinct panels. This is deliberate: in Power Query, the "Replace Values" dialog and the "Replace Errors" dialog are entirely separate UI actions, reflecting the engine's internal distinction. A common beginner mistake is to use "Replace Values" to fix error cells—it will have no effect, because errors are not values; they are exceptions. Conversely, "Replace Errors" will not affect null cells. The preventive panel on the right emphasizes that the most robust approach is to reduce the occurrence of nulls and errors by applying type conversions and validations early in the query pipeline.

How It Works — M Language Constructs for Nulls & Errors

Power Query's graphical interface ultimately generates code in the M language (formally known as the Power Query Formula Language). Understanding the M constructs behind null and error handling gives you the precision of programmatic control while still allowing you to use the GUI for routine tasks. The key constructs are the null literal, the equality operator's behavior with null, the try expression, and the ?? (null coalescing) operator.

Null Detection & Replacement

NULL COALESCING OPERATOR
result = value ?? defaultValue
If value is null, return defaultValue; otherwise return value. Equivalent to if value = null then defaultValue else value. This is analogous to Python's value if value is not None else default or C#'s ?? operator.

Error Handling with try...otherwise

TRY EXPRESSION
result = try riskyExpression otherwise fallbackValue
Evaluates riskyExpression. If it produces a value, result receives that value. If it raises an error, result receives fallbackValue. Without the otherwise clause, try returns a record with fields HasError, Value, and Error.

GUI-Generated M Code Examples

Common GUI actions and their equivalent M code in Power Query.
GUI ActionGenerated M CodeEffect
Replace Values (null → 0)Table.ReplaceValue(prev, null, 0, Replacer.ReplaceValue, {"Amount"})Every null in the Amount column becomes 0.
Replace Errors (→ null)Table.ReplaceErrorValues(prev, {{"Price", null}})Every error cell in Price becomes null.
Remove ErrorsTable.RemoveRowsWithErrors(prev, {"Price"})Entire rows with errors in Price are dropped.
Fill DownTable.FillDown(prev, {"Region"})Nulls in Region are replaced by the last non-null value above.
Null vs. Blank String
A frequent source of confusion: an empty text value "" is not the same as null. A blank string is a valid text value of length zero. Power Query's "Replace Values" dialog can target either, but you must specify the correct one. In CSV imports, truly empty cells usually parse as null, while cells containing whitespace-only strings do not.

Classification of Missing-Value Patterns

In statistical and data-engineering literature, missing data is classified into three categories formalized by Donald Rubin in 1976. While Power Query does not explicitly label data this way, understanding the taxonomy helps you choose the correct remediation strategy. A value that is Missing Completely at Random (MCAR) is independent of both observed and unobserved variables—dropping these rows introduces no bias. A value that is Missing at Random (MAR) depends on other observed variables but not on the missing value itself—imputation using correlated columns can be effective. A value that is Missing Not at Random (MNAR) depends on the missing value itself—for example, high-income respondents refusing to disclose salary. MNAR requires domain expertise to address.

A five-row sample table illustrating different missing-value patterns. Null cells are highlighted in amber; the error cell (Margin% for Row 4, likely caused by a division-by-zero in a calculated column) is highlighted in red. Only Row 1 is fully valid. The summary panels at the bottom show the distribution of issues across the dataset.
Rubin's missing-data taxonomy mapped to Power Query remediation strategies.
Missing PatternDefinitionPower Query Strategy
MCARMissingness is unrelated to any variable. Safe to drop rows or impute with column mean/median.Remove Rows containing nulls, or Replace Values with a global constant (0, mean).
MARMissingness depends on observed data (e.g., Region predicts Revenue nulls). Imputation should condition on observed variables.Conditional Column or Merge with a lookup table to impute based on related columns.
MNARMissingness depends on the unobserved value itself. No purely data-driven fix; requires domain knowledge.Flag with a Boolean indicator column; document the limitation for report consumers.

Worked Example — Cleaning a Sales Dataset

Consider a CSV file containing quarterly sales records. After importing it into Power Query, you notice several issues: the Revenue column has null values for some rows, the Region column has nulls that should be filled from the row above (a common pattern in exports from grouped reports), and a computed Margin% column shows errors where Revenue was zero, causing a division-by-zero. The worked example below walks through a complete remediation sequence.

Cleaning Nulls and Errors in a Sales Query
1
Step 1 — Enable Column Quality IndicatorsIn the Power Query Editor, go to the View tab and check Column Quality. Power Query displays a bar at the top of each column showing the percentage of values that are Valid, Error, or Empty (null). This gives you immediate visibility into the scope of the problem. For our dataset, Revenue shows 80% Valid and 20% Empty; Margin% shows 80% Valid and 20% Error.
Column Quality bars visible: Revenue → 20% Empty, Margin% → 20% Error.
2
Step 2 — Fill Down the Region ColumnSelect the Region column. Navigate to Transform → Fill → Down. This applies Table.FillDown(prevStep, {"Region"}), propagating the last non-null Region value into subsequent null cells. This is appropriate because the source report grouped rows under regional headers, and the blanks represent continuation of the same group—a classic MAR pattern.
Region column: 0% Empty after fill-down.
3
Step 3 — Replace Null Revenue with 0Select the Revenue column, right-click, and choose Replace Values. Set "Value To Find" to null and "Replace With" to 0. The generated M code is: Table.ReplaceValue(prevStep, null, 0, Replacer.ReplaceValue, {"Revenue"}). Important: this decision assumes that a missing Revenue genuinely means zero sales, not "data not yet available." Document this assumption.
Revenue column: 100% Valid, all nulls replaced with 0.
4
Step 4 — Fix the Margin% Errors Using try...otherwiseThe Margin% error cells were caused by dividing Profit by Revenue when Revenue = 0. Rather than simply replacing errors, we fix the root cause. Select the Margin% column, go to Add Column → Custom Column, and enter: if [Revenue] = 0 then 0 else [Profit] / [Revenue] * 100. Alternatively, to handle any unexpected error gracefully, wrap the expression: try ([Profit] / [Revenue] * 100) otherwise 0. Remove the original Margin% column and rename the new one.
New Margin% column: 100% Valid, no error cells.
5
Step 5 — Validate with Column QualityRe-check the Column Quality indicators across all columns. Every column should now show 100% Valid. Additionally, enable Column Distribution and Column Profile (also on the View tab) to confirm that the distribution of replaced values looks reasonable. If a high percentage of Revenue values are now zero, you may want to add a Boolean indicator column IsImputedRevenue so downstream analysts can filter or annotate affected records.
All columns 100% Valid. Query is clean and ready for loading into the data model.

Strengths, Limitations & Strategy Comparison

Each null and error handling strategy in Power Query involves tradeoffs. Removing rows is the simplest approach but reduces dataset size and may introduce bias. Replacing with defaults (zero, mean, empty string) preserves row counts but can distort distributions. Fill Down is elegant for hierarchical data but dangerous if applied to the wrong column—it assumes the positional ordering is meaningful. The try...otherwise construct is the most flexible but adds complexity to M code and can mask upstream issues if overused. The table below provides a systematic comparison.

Comparison of null and error handling strategies in Power Query.
StrategyStrengthsLimitations
Remove RowsSimple; guarantees no nulls/errors in output; appropriate for MCAR data with low missingness rates.Reduces sample size; introduces selection bias if data is MAR or MNAR; irreversible in the query.
Replace Values (constant)Preserves all rows; easy to implement via GUI; good for known sentinel values (e.g., 0 for count fields).Distorts mean, variance, and distributions; the chosen constant may not be semantically correct.
Fill Down / Fill UpPerfect for hierarchically grouped data (e.g., pivot table exports); preserves logical structure.Assumes row ordering is stable and meaningful; incorrect if nulls represent genuinely missing data rather than implied repetition.
Replace ErrorsQuick fix for known error patterns; allows replacing with null for deferred handling downstream.Masks root cause; if the upstream error changes, the replacement may become inappropriate.
try...otherwise (M)Maximum flexibility; can inspect error details and branch on reason; can log error metadata.Requires M proficiency; overuse can hide bugs; adds formula complexity and may reduce query folding.
KEY TAKEAWAY
Choosing a missing-value strategy is analogous to choosing an exception-handling policy in a software system. Just as you wouldn't wrap every line of Java in a try-catch that swallows all exceptions, you shouldn't blindly replace all errors in Power Query. The best approach is defensive but transparent: handle known patterns explicitly, log or flag ambiguous cases, and let genuine data-source failures surface as errors so they trigger investigation rather than silent data corruption.

Connection to Advanced Data Quality Techniques

The introductory techniques covered in this lesson—replacing, removing, and filling—are the first layer of a multi-layered data quality strategy. As you advance in Power BI development, you will encounter scenarios that demand more sophisticated handling. DAX measures in the data model use functions like ISBLANK() and IF(ISBLANK(...),...) to handle nulls at calculation time rather than at ingestion time—this is useful when the correct imputation depends on the report's filter context. In advanced scenarios, you may build data quality dimensions (completeness scores, freshness indicators) as separate tables that inform automated alerting.

Introductory vs. advanced null/error handling in the Power BI ecosystem.
AspectIntro (This Lesson)Advanced
Where handling occursPower Query (ETL layer) — nulls and errors are resolved before loading into the model.Both Power Query and DAX — some handling deferred to measures for context-dependent imputation.
Imputation complexityConstant replacement (0, mean), fill down/up, remove row.Statistical imputation (median by group, regression-based), ML-powered imputation in Dataflows.
Error handlingReplace Errors with a constant; Remove Errors to drop entire rows.Error routing to separate audit tables; structured try-catch with metadata logging; retry logic for transient API failures.
ObservabilityManual inspection via Column Quality, Column Distribution, Column Profile.Automated data quality scorecards; Power Automate alerts on threshold breaches; lineage tracking in Fabric.

As you progress through data engineering coursework, you will also encounter the concept of query folding—Power Query's ability to push transformation logic back to the data source (e.g., generating SQL). Not all null/error handling operations fold. Operations like Table.ReplaceValue for null replacement typically fold to a SQL COALESCE or ISNULL, while try...otherwise blocks and custom M functions generally break folding. This performance consideration becomes critical at enterprise scale.

Practice Problems

PROBLEM 1CONCEPTUAL
Explain the difference between a null cell and an Error cell in Power Query. Why does the "Replace Values" dialog not affect error cells, and vice versa for "Replace Errors"?
PROBLEM 2BASIC CALCULATION
A Power Query table has 500 rows. The Column Quality indicator for the Salary column shows 88% Valid, 8% Empty, and 4% Error. How many rows contain a null Salary? How many contain an error? If you apply "Remove Errors" on the Salary column, how many rows remain?
PROBLEM 3INTERMEDIATE
You import a CSV where the OrderDate column contains dates in the format "MM/DD/YYYY" but some cells contain the text "N/A". After Power Query auto-detects the column as type Date, those cells become errors. Describe two different approaches to handling this in Power Query (one GUI-based, one M-based), and discuss which preserves more information.
PROBLEM 4APPLIED
You are building a Power BI report for a retail chain. The source data comes from 50 store databases merged via a Power Query append. Some stores use 0 for "no sales" and others leave the cell blank (null). Your report contains a DAX measure Avg Sales = AVERAGE(Sales[Revenue]). Explain how this inconsistency affects the average, and propose a Power Query solution that normalizes the data without distorting the aggregate.
PROBLEM 5CRITICAL THINKING
A colleague proposes adding try ... otherwise null around every custom column formula in the Power Query pipeline to ensure the dataset never contains error cells. Critique this approach from the perspectives of (a) data integrity, (b) debugging and maintainability, and (c) performance (query folding). Under what circumstances, if any, would this blanket approach be acceptable?

Summary — Handling Missing Values in Power Query

Power Query distinguishes between two categories of problematic cells: nulls (valid markers for absent data that propagate through expressions) and errors (failed computations that carry diagnostic metadata). The GUI provides distinct commands for each— Replace Values and Fill Down for nulls, Replace Errors and Remove Errors for error cells—while the M language offers the ?? (null coalescing) operator and try...otherwise expressions for fine-grained control.

Choosing the right strategy requires understanding the missingness pattern (MCAR, MAR, MNAR) and the business semantics of the data. The Column Quality indicator in Power Query Editor is your first diagnostic tool—enable it at the start of every data preparation session. The guiding principle is defensive but transparent: handle known patterns explicitly, flag ambiguous cases with indicator columns, and avoid blanket error suppression that could mask upstream data quality issues.

Varsity Tutors • Microsoft Power BI • Handling Missing Values — Handle missing values and errors (nulls, error rows) (intro)