Data Transformation in Microsoft Fabric: Joins, Deduplication and Nulls
Introduction
Data transformation in Microsoft Fabric turns source rows into reliable analytical tables. In this DP-600 lesson, you will compare Dataflow Gen2, T-SQL and PySpark for joining, aggregating, deduplicating and parsing data. The examples show how to detect bad input and preserve the intended row counts.
Learning objectives
- Aggregate data with group-by operations in Power Query, T-SQL and PySpark.
- Choose the right join type and merge or append datasets.
- Identify and resolve duplicates, missing data and nulls.
- Convert data types safely and filter rows and columns early.
- Choose a transformation tool and understand query folding.
1. Choosing a transformation tool
| Tool | Strength | Typical user | Limit |
|---|---|---|---|
| Dataflow Gen2 (Power Query) | Visual transformations and source query folding | Analyst | Performance depends on the connector, folding and workload |
| Notebook (PySpark / Spark SQL) | Scale, code control, complex logic, ML | Data engineer | Requires coding skills |
| T-SQL in a warehouse | Set-based SQL, transactions, stored procedures | SQL developer | Use a Warehouse for T-SQL writes. The lakehouse endpoint reads table data |
| KQL in an eventhouse | Time-series and streaming transformations (update policies) | Real-time analyst | Specific to KQL databases |
| Pipeline Copy activity | Movement, light mapping | Data engineer | Not for rich transformation |
Query folding. Power Query can delegate supported transformations to a source such as Azure SQL. Folding can be full, partial or absent, depending on the connector and the steps. A custom function or added index can leave work for the mashup engine. Move independent filters and projections early when that preserves the result, then inspect the folding indicators. Dataflow Gen2 staging can let Fabric compute handle transformations that do not fold to the original source. Compare refresh cost before choosing it. For source setup, see Fabric ingestion and connection options.
2. Aggregating data with SQL, Power Query and PySpark
An aggregation reduces rows to summary values (sum, count, average, min, max, distinct count) per group.
Power Query: Home → Group by, then choose one or more key columns and operations. The M code is Table.Group.
T-SQL:
SELECT CustomerKey,
YEAR(OrderDate) AS OrderYear,
SUM(Quantity * UnitPrice) AS Revenue,
COUNT(DISTINCT OrderID) AS Orders
FROM dbo.FactSales
GROUP BY CustomerKey, YEAR(OrderDate)
HAVING SUM(Quantity * UnitPrice) > 10000;WHERE filters rows before grouping; HAVING filters groups after aggregation.
PySpark:
from pyspark.sql import functions as F
agg = (df.groupBy("CustomerKey", F.year("OrderDate").alias("OrderYear"))
.agg(F.sum(F.col("Quantity")*F.col("UnitPrice")).alias("Revenue"),
F.countDistinct("OrderID").alias("Orders")))Use a separate aggregate table when a recurring query needs only a coarser grain. Keep the detailed fact for drill-down and reconcile totals between the two tables. Before choosing the summary keys, design a Fabric star schema and define its grain.
Example. Northwind keeps 400 million order lines. A daily sales dashboard needs only totals by store and day. A summary table AggSalesStoreDay of 2 million rows serves it, while the detailed fact stays for investigations.
3. Merging and joining data
Combining datasets comes in two forms: horizontal (join/merge: add columns) and vertical (union/append: add rows).
| Join type | Rows returned | Power Query name |
|---|---|---|
| Inner | Only matching rows from both | Inner |
| Left outer | All left rows, matching right | Left outer |
| Right outer | All right rows, matching left | Right outer |
| Full outer | All rows from both | Full outer |
| Left anti | Left rows with no match | Left anti |
| Right anti | Right rows with no match | Right anti |
| Cross | Every combination | Use a custom expansion pattern |
-- customers who never ordered (left anti)
SELECT c.CustomerKey
FROM dbo.DimCustomer c
LEFT JOIN dbo.FactSales s ON s.CustomerKey = c.CustomerKey
WHERE s.CustomerKey IS NULL;customers.join(orders, on="CustomerKey", how="left_anti")Points to remember:
- Normalize join key types and formats explicitly. For identifier strings, decide whether leading zeros are meaningful before casting. Some engines coerce types implicitly, which can change matches or cause conversion errors.
- A join emits each matching pair. If a lookup key appears twice on the right, one matching fact row becomes two. Check uniqueness on the intended one side before joining.
- Append (UNION ALL in SQL,
unionByNamein Spark, Append queries in Power Query) stacks datasets with aligned columns and compatible types. SQL matches by position, while SparkunionByNamematches by name.UNIONremoves duplicate result rows.UNION ALLretains them without the distinct operation. - In Power Query, Merge queries creates a nested column that you expand; choose only the needed columns.
Worked example: choosing the join
Statement. A retailer has Sales (5 million rows) and Stores (400 rows). Some sales rows reference store IDs missing from Stores. The analyst wants to keep every sale and show "Unknown" when the store is missing.
Reasoning. Every sale must be kept, so Sales is the preserved side: a left outer join from Sales to Stores. Missing stores produce nulls in store columns, which are then replaced with "Unknown".
Solution. SELECT s.*, COALESCE(st.StoreName,'Unknown') AS StoreName FROM Sales s LEFT JOIN Stores st ON st.StoreID = s.StoreID.
Why the other choices are worse. An inner join silently drops sales with unknown stores, understating revenue. A full outer join adds stores that never sold, which are not needed. A right outer join preserves the wrong table.
4. Duplicates
Duplicates arise from repeated loads, overlapping extracts, double events and many-to-many joins. First define what makes a row a duplicate (all columns, or a business key such as OrderID).
Power Query: use Remove duplicates when any survivor is acceptable. Sorting alone does not guarantee which row Table.Distinct keeps. When the version matters, rank rows by a timestamp and a stable tie-breaker in the source, or group by key and select the first row after sorting within each group. Buffering a sorted table can make distinct selection predictable, but it consumes memory and prevents downstream folding.
T-SQL (keep the latest row per key):
WITH ranked AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY OrderID ORDER BY ModifiedAt DESC, IngestID DESC) AS rn
FROM stg.Orders
)
SELECT * FROM ranked WHERE rn = 1;PySpark:
from pyspark.sql import Window, functions as F
w = Window.partitionBy("OrderID").orderBy(F.col("ModifiedAt").desc_nulls_last(), F.col("IngestID").desc())
dedup = df.withColumn("rn", F.row_number().over(w)).filter("rn = 1").drop("rn")
# These are alternatives when version selection is unnecessary.
exact_dedup = df.dropDuplicates()
key_dedup = df.dropDuplicates(["OrderID"])Here IngestID uniquely orders rows within an order when timestamps tie. Without a tie-breaker, a window can also choose different survivors across runs. dropDuplicates(["key"]) removes duplicate keys without choosing a business-defined version.
5. Missing data and nulls
NULL represents a missing or inapplicable value. An empty string and zero carry different meanings. Nulls propagate: NULL + 5 is NULL, NULL = NULL is not true, and aggregates such as SUM and AVG ignore nulls (so AVG of three values with one null divides by two).
Strategies:
| Strategy | When | Example |
|---|---|---|
| Remove from the trusted result | A required key is missing | Quarantine orders without OrderID |
| Replace with a constant | A business default is meaningful | Replace null region with "Unknown" |
| Replace with a statistic | Numeric analysis, ML | Fill with median |
| Fill down / up | Ordered data, grouped labels | Excel-style merged cells in Power Query |
| Leave as null | Absence is meaningful | No end date means still active |
| Flag | Keep the information that it was missing | IsEmailMissing column |
SELECT COALESCE(Region, 'Unknown') AS Region,
ISNULL(Discount, 0) AS Discount,
NULLIF(Quantity, 0) AS SafeQuantity
FROM dbo.Sales;df.fillna({"Region": "Unknown", "Discount": 0})
df.na.drop(subset=["OrderID"])Power Query offers Replace values, Fill → Down, Remove empty, and Replace errors. Sort and group before filling down when labels must not cross groups.
Distinguish errors from nulls: a failed conversion creates an error in Power Query (Table.RemoveRowsWithErrors, Replace errors) or a conversion error in SQL. TRY_CAST returns NULL for a value it cannot convert when the conversion is permitted. Keep the original input or a flag so a parse failure remains distinguishable from an originally missing value.
Example. A hospital's patient table has DischargeDate null for current inpatients. Replacing it with 1900-01-01 would produce absurd stays. Keeping null and computing length of stay with COALESCE(DischargeDate, CAST(GETDATE() AS date)) keeps the meaning.
6. Converting data types
Correct types matter for correctness, compression and relationships.
- Dates stored as text ("12/03/2026") are ambiguous: the locale decides whether it is 12 March or 3 December. In Power Query use Using Locale when changing type; in SQL use
TRY_CONVERT(date, col, 103)with a style; in Spark parse with an explicit format, for exampletry_to_timestampfollowed by a date cast. - Numbers as text with currency symbols or thousands separators need cleaning before casting.
- Decimal vs float: use fixed-precision
decimal(18,2)for money; floating point can create rounding noise. - Choose the smallest suitable type (int vs bigint, date vs datetime) for compression and speed.
SELECT TRY_CAST(Amount AS decimal(18,2)) AS Amount,
TRY_CONVERT(date, OrderDateText, 103) AS OrderDate
FROM stg.Orders;from pyspark.sql import functions as F
clean = df.withColumn(
"AmountParsed", F.expr("try_cast(trim(Amount) AS DECIMAL(18,2))")
).withColumn(
"OrderDate", F.try_to_timestamp("OrderDateText", F.lit("dd/MM/yyyy")).cast("date")
)
invalid_dates = clean.filter(
F.col("OrderDateText").isNotNull() & F.col("OrderDate").isNull()
)The amount example assumes a decimal point and no thousands separator. Parse each source with its known locale or normalize it before conversion. Count invalid values and quarantine them when they would distort totals or dates.
7. Filtering data
Filter rows and columns as early as possible.
- Remove rows that are never needed (test records, cancelled orders, dates before the business start).
- Remove unused columns: fewer columns means smaller models and faster refresh.
- In Power Query, check whether the connector can fold each filter. Confirm that moving the filter earlier does not change which records should survive.
- In Spark, filters on partition columns allow partition pruning; predicate pushdown applies to Delta and Parquet.
- Use a parameter (for example a start date) for dynamic filtering and incremental refresh later.
SELECT OrderID, OrderDate, Amount
FROM dbo.Orders
WHERE OrderDate >= '2024-01-01' AND Status <> 'Cancelled';Mind three-valued logic: WHERE Status <> 'Cancelled' also removes rows where Status is NULL. If nulls must be kept, write WHERE Status <> 'Cancelled' OR Status IS NULL.
Worked example: a cleaning sequence
Statement. A Dataflow Gen2 reads a 30-million-row Orders table from Azure SQL Database. Rows include test orders (CustomerID = 0), duplicate OrderIDs from a double extract, text amounts like "1,250.50", and 2% of rows missing Region. The refresh is slow and the final dataflow must be correct.
Reasoning. Filter test rows and keep only needed columns, including the key and the columns used to choose the latest version. Confirm that the source can fold the filter. Rank the remaining rows by ModifiedAt and a unique ingestion ID. Parse the amount with the source culture and record conversion errors. Flag missing regions before replacing them with "Unknown".
Solution. Filter and project → select a deterministic survivor → parse and flag errors → flag and fill missing regions. This order assumes the test records are independent of valid versions. If the newest record can invalidate an older one, choose the latest version before applying the business filter.
8. Putting it in the right tool: decision table
| Scenario | Best tool |
|---|---|
| Analyst cleans an Excel and a SQL table, no code | Dataflow Gen2 |
| 2 billion rows, complex window logic | Notebook |
| Nightly SCD loads in a warehouse | T-SQL stored procedure |
| Keep the latest event per ID across ingestion batches | Eventhouse materialized view using an appropriate aggregation such as arg_max |
| Move data unchanged | Pipeline Copy activity |
9. Equivalent operations across languages
| Operation | Power Query (M) | T-SQL | PySpark |
|---|---|---|---|
| Filter rows | Table.SelectRows |
WHERE |
filter / where |
| Select columns | Table.SelectColumns |
SELECT col |
select |
| Group and sum | Table.Group |
GROUP BY |
groupBy().agg() |
| Join | Table.NestedJoin |
JOIN |
join |
| Append | Table.Combine |
UNION ALL |
unionByName |
| Remove duplicates | Table.Distinct |
ROW_NUMBER() / DISTINCT |
dropDuplicates |
| Replace null | Table.ReplaceValue |
COALESCE / ISNULL |
fillna |
| Change type | Table.TransformColumnTypes |
TRY_CAST |
cast |
Knowing the equivalence lets you answer a question in any of the three languages. A frequent trap is a scenario stating the team's skills: choose the tool they already master, provided it meets the volume requirement. Another is idempotency: a transformation should produce the same result when rerun. For example, merge a deduplicated source using a stable key, or overwrite a complete target partition. Keep the write scope and input consistent on retry.
Common pitfalls
- Using an inner join and losing rows without noticing.
- Joining on columns with different types or hidden whitespace.
- Treating NULL like zero or an empty string.
- Removing duplicates without defining the key or order.
- Converting dates without specifying the locale.
- Filtering after the expensive steps and breaking query folding.
- Using
NOT INagainst a nullable lookup. An unmatched comparison can evaluate to UNKNOWN. UseNOT EXISTSfor the anti-join.
Exam tip: when a scenario says "keep all records from X", think left (or right) outer join. When it says "records in X with no match in Y", think anti join. When it says "performance of a Dataflow", think query folding, filtering early and staging.
Mini case study
Wingtip Toys loads orders from two regional ERPs into a lakehouse. Problems reported: revenue is 7% too high, some customers appear twice with different capitalisations, 4% of orders have no sales region, and the date column is text in two different formats.
Proposed solution.
- Parse dates using each ERP's documented format before appending the feeds. Preserve the source ID and source business key.
- Confirm whether overlapping extracts contain the same business orders. If ERP keys are only unique locally, use a crosswalk to identify shared orders. Append the normalized feeds with
unionByNameand select one version per canonical order key with a deterministic window. - Use stable customer identifiers for the dimension join. Trim and normalize descriptive names for display. Keep unmatched orders with a left outer join and track them for data quality review.
- Add
IsRegionMissingbefore filling the region with "Unknown". Apply the cancellation rule to the chosen version of each order and keep the required output columns.
Commentary. Reconcile the order count and revenue before and after each step. The expected result is one row at the declared order grain, with unknown attributes visible to the steward.
Key terms
- Aggregation: reducing rows to summary values per group.
- Join / merge: combining datasets horizontally.
- Append / union: combining datasets vertically.
- Anti join: rows with no match in the other table.
- Deduplication: keeping one row per defined key.
- NULL: unknown or absent value.
- TRY_CAST / TRY_CONVERT: conversions that return NULL on failure.
- Query folding: pushing Power Query steps to the source.
- Partition pruning: skipping partitions that cannot match a filter.
Summary checklist
- I can aggregate with Power Query, T-SQL and PySpark and distinguish WHERE from HAVING.
- I can choose between inner, outer, anti and cross joins and between UNION and UNION ALL.
- I can deduplicate with an explicit key and order.
- I know the strategies for nulls and the effect of nulls on aggregates and comparisons.
- I can convert text to dates and numbers safely with locale and TRY_ functions.
- I filter rows and columns early and preserve query folding.
Official sources
- Study guide for Exam DP-600: https://learn.microsoft.com/en-us/credentials/certifications/resources/study-guides/dp-600 (opens in a new tab)
- Dataflow Gen2 overview: https://learn.microsoft.com/en-us/fabric/data-factory/dataflows-gen2-overview (opens in a new tab)
- Query folding in Power Query: https://learn.microsoft.com/en-us/power-query/query-folding-basics (opens in a new tab)
- Power Query duplicate retention: https://learn.microsoft.com/en-us/powerquery-m/table-distinct (opens in a new tab)
- Dataflow Gen2 staging: https://learn.microsoft.com/en-us/fabric/data-factory/data-in-staging-items (opens in a new tab)
- PySpark safe date parsing: https://spark.apache.org/docs/3.5.9/api/python/reference/pyspark.sql/api/pyspark.sql.functions.try_to_timestamp.html (opens in a new tab)
- Transact-SQL reference for Fabric Data Warehouse: https://learn.microsoft.com/en-us/fabric/data-warehouse/tsql-surface-area (opens in a new tab)
