Contents

Chapter 1

Power Query M — Common Errors & Fixes

A troubleshooting reference for the errors you'll encounter most often when

adapting these templates to your own data.


Error: "Expression.Error: The column 'X' of the table wasn't found."

Cause: You referenced a column name that doesn't exist in your data.

Common triggers:

  • Source renamed a column (e.g., "Revenue" → "Total Revenue")
  • Typo in column name (case-sensitive!)
  • Column was removed in an earlier step

Fix:

m
// Check actual column names first:
Table.ColumnNames(YourTable)

// Use try...otherwise for optional columns:
try YourTable[MaybeColumn] otherwise null

Error: "DataFormat.Error: We couldn't convert to Number."

Cause: A cell that should be numeric contains text (e.g., "N/A", "-", "TBD").

Fix:

m
// Replace non-numeric sentinels BEFORE type conversion:
Cleaned = Table.ReplaceValue(Source, "N/A", null, Replacer.ReplaceValue, {"Amount"}),
Typed = Table.TransformColumnTypes(Cleaned, {{"Amount", type number}})

// Or use try per-row:
Table.AddColumn(Source, "SafeAmount", each
    try Number.From([RawAmount]) otherwise null, type nullable number)

Error: "Formula.Firewall: Query references other queries or steps..."

Cause: Power Query's privacy firewall is blocking a cross-source operation

(e.g., using a parameter from one source to filter another).

Fix (development):

  • Excel: File → Options → Query Options → Privacy → "Always ignore Privacy Level settings"
  • Power BI: File → Options → Global → Privacy → "Always ignore"

Fix (production): Set both sources to "Organizational" privacy level in Data Source Settings.


Error: "DataSource.Error: Could not find file 'C:\path\file.csv'."

Cause: Hardcoded file path doesn't exist on this machine (common when

sharing workbooks between team members).

Fix: Use a parameter for the base path:

m
// Define parameter "BasePath" = "C:\Users\YourName\Data\"
// Then reference it:
Source = Csv.Document(File.Contents(BasePath & "filename.csv"))

Error: "Expression.Error: There weren't enough elements in the enumeration..."

Cause: You tried to access a row by index (e.g., Table{0}) but the table is empty.

Fix:

m
// Use try...otherwise:
FirstRow = try Source{0} otherwise null

// Or check first:
if Table.RowCount(Source) > 0 then Source{0} else null

Error: "Expression.Error: We cannot apply operator & to types Number and Text."

Cause: Concatenation (&) only works on text values. One side is a number.

Fix:

m
// Convert to text explicitly:
Combined = Text.From([Year]) & "-" & Text.From([Month])

Error: "Key didn't match any rows in the table" (during join)

Cause: The lookup value doesn't exist in the target table. This isn't always

an error — it may just be a missing reference.

Fix:

m
// Use LeftOuter join (keeps all rows from left table, nulls for no-match):
Table.NestedJoin(Source, {"Key"}, Lookup, {"Key"}, "Matched", JoinKind.LeftOuter)

// Then handle nulls in the expanded columns

Query Runs Forever (No Error, Just Slow)

Common causes:

1. Broken query folding — Check by right-clicking a step → "View Native Query".

If grayed out, folding broke. Move non-foldable steps to the end.

2. Cartesian join — You joined two tables without proper keys, creating

an N×M explosion. Verify join columns have matching values.

3. List.Contains on unbuffered list — Buffer the list first:

m
   BufferedIDs = List.Buffer(LookupTable[ID])

4. Recursive function without depth limit — Add a max-depth parameter.


"This step results in an error for some rows"

Cause: Some rows have values that can't be processed by a transform

(e.g., date parsing fails on "Unknown").

Diagnosis:

m
// Keep error rows for inspection:
Errors = Table.SelectRowsWithErrors(Source, {"ProblematicColumn"})

Fix: Clean the data BEFORE the failing step, or use try:

m
Table.AddColumn(Source, "SafeDate", each
    try Date.FromText([DateString]) otherwise null)

Parameter Refresh Issues in Power BI Service

Symptom: Query works in Desktop but fails after publishing to Service.

Common causes:

  • File path parameters (Service can't access local drives)
  • Dynamic data sources (Gateway doesn't recognize parameterized URLs)
  • Privacy level conflicts in the cloud

Fix:

  • Use Web URLs or SharePoint paths instead of local file paths
  • Ensure dynamic URLs are marked as "Organizational" privacy
  • Configure Gateway data source to match the parameterized connection

Best Practices to Avoid Errors

1. Always specify data types explicitly — Don't rely on auto-detection

2. Use try...otherwise for any operation that might fail per-row

3. Buffer lists before using them in List.Contains

4. Keep foldable operations at the top of your query

5. Use Table.ColumnNames to verify schema before referencing columns

6. Test with a small sample (Table.FirstN(Source, 100)) during development


Part of Data Analyst Toolkit

Chapter 2

Power Query M — Function Quick Reference

The most useful M functions organized by category, with signatures and one-line descriptions.

This covers functions used throughout the 58 templates in this collection.


Table Functions

FunctionSignaturePurpose
Table.SelectRows(table, condition)Filter rows by a boolean condition
Table.SelectColumns(table, columns)Keep only named columns
Table.RemoveColumns(table, columns)Drop named columns
Table.AddColumn(table, name, fn, type?)Add computed column
Table.RenameColumns(table, renames)Rename columns via pairs list
Table.ReorderColumns(table, order)Change column display order
Table.TransformColumnTypes(table, transforms)Set/change column data types
Table.TransformColumns(table, transforms)Apply function to column values
Table.ReplaceValue(table, old, new, replacer, cols)Find and replace in columns
Table.Sort(table, criteria)Sort by one or more columns
Table.Group(table, keys, aggregations)Group by keys with aggregations
Table.Distinct(table, columns?)Remove duplicate rows
Table.FirstN(table, n)Take first N rows
Table.Skip(table, n)Skip first N rows
Table.RowCount(table)Count rows in table
Table.ColumnNames(table)Get list of column names
Table.Combine(tables)Stack tables vertically (UNION)
Table.PromoteHeaders(table, options?)Use first row as column headers
Table.Pivot(table, pivotValues, attrCol, valCol, aggFn)Rows → columns
Table.Unpivot(table, columns, attrName, valName)Named columns → rows
Table.UnpivotOtherColumns(table, fixedCols, attrName, valName)All OTHER columns → rows
Table.FuzzyJoin(left, lKeys, right, rKeys, kind, opts)Approximate join
Table.FuzzyGroup(table, col, aggregations, opts)Cluster similar values
Table.NestedJoin(left, lKeys, right, rKeys, name, kind)Join with nested result
Table.ExpandTableColumn(table, col, subCols, newNames?)Flatten nested table column
Table.Buffer(table)Force evaluation, cache in memory
Table.Partition(table, col, partitions, fn)Split into N sub-tables
Table.FromRecords(records, schema?, missingField?)Record list → table
Table.SelectRowsWithErrors(table, columns?)Keep only error rows
Table.RemoveRowsWithErrors(table, columns?)Drop error rows

Text Functions

FunctionSignaturePurpose
Text.Trim(text)Remove leading/trailing whitespace
Text.Clean(text)Remove non-printable characters
Text.Upper(text)Convert to uppercase
Text.Lower(text)Convert to lowercase
Text.Proper(text)Title Case conversion
Text.Start(text, n)First N characters
Text.End(text, n)Last N characters
Text.Range(text, offset, count?)Substring by position
Text.Contains(text, substring, comparer?)Check if text contains value
Text.StartsWith(text, prefix, comparer?)Check prefix
Text.EndsWith(text, suffix, comparer?)Check suffix
Text.Split(text, separator)Split into list by delimiter
Text.Combine(list, separator?)Join list into text
Text.Replace(text, old, new)Replace substring
Text.Remove(text, chars)Remove specific characters
Text.Select(text, chars)Keep only specified characters
Text.BeforeDelimiter(text, delim, opts?)Text before first delimiter
Text.AfterDelimiter(text, delim, opts?)Text after first delimiter
Text.BetweenDelimiters(text, start, end)Text between two delimiters
Text.Length(text)Character count
Text.From(value)Convert any value to text
Text.ToList(text)Split into character list
Text.PadStart(text, count, char?)Left-pad to length

Number Functions

FunctionSignaturePurpose
Number.From(value)Convert to number
Number.Round(number, digits?)Round to N decimals
Number.RoundUp(number, digits?)Round up (ceiling)
Number.RoundDown(number, digits?)Round down (floor)
Number.Abs(number)Absolute value
Number.Sign(number)Returns -1, 0, or 1
Number.Mod(number, divisor)Modulo (remainder)
Number.Power(base, exponent)Exponentiation
Number.Sqrt(number)Square root
Number.Log(number, base?)Logarithm
Number.Max(x, y)Larger of two values
Number.Min(x, y)Smaller of two values

Date & Time Functions

FunctionSignaturePurpose
Date.From(value)Convert to date
Date.FromText(text, options?)Parse text to date
Date.ToText(date, format?)Format date as text
Date.Year(date)Extract year
Date.Month(date)Extract month (1-12)
Date.Day(date)Extract day of month
Date.DayOfWeek(date, firstDayOfWeek?)Day of week (0-6)
Date.DayOfYear(date)Day of year (1-366)
Date.WeekOfYear(date, firstDayOfWeek?)Week number
Date.QuarterOfYear(date)Quarter (1-4)
Date.StartOfMonth(date)First day of month
Date.EndOfMonth(date)Last day of month
Date.StartOfWeek(date, firstDayOfWeek?)First day of week
Date.StartOfQuarter(date)First day of quarter
Date.AddDays(date, n)Add/subtract days
Date.AddMonths(date, n)Add/subtract months
Date.AddYears(date, n)Add/subtract years
DateTime.LocalNow()Current local datetime
DateTime.Date(datetime)Extract date part
Duration.Days(duration)Duration → day count
#date(year, month, day)Construct a date value
#datetime(y, m, d, h, min, s)Construct a datetime value
#duration(d, h, m, s)Construct a duration value

List Functions

FunctionSignaturePurpose
List.Count(list)Number of elements
List.Sum(list)Sum of numeric values
List.Average(list)Arithmetic mean
List.Max(list)Maximum value
List.Min(list)Minimum value
List.Median(list)Median value
List.Distinct(list)Unique values only
List.Sort(list, order?)Sort ascending/descending
List.First(list, default?)First element
List.Last(list, default?)Last element
List.FirstN(list, n)First N elements
List.LastN(list, n)Last N elements
List.Select(list, condition)Filter list by condition
List.Transform(list, fn)Map function over list
List.Accumulate(list, seed, fn)Reduce/fold over list
List.Generate(init, cond, next, selector?)Generate list iteratively
List.Contains(list, value)Check membership
List.Combine(lists)Concatenate multiple lists
List.Intersect(lists)Common elements
List.Union(lists)All unique elements from all lists
List.RemoveItems(list, items)Remove specified values
List.Buffer(list)Force evaluation, cache
List.Zip(lists)Pair elements from parallel lists
List.Positions(list)List of index positions {0..n-1}

Record Functions

FunctionSignaturePurpose
Record.Field(record, fieldName)Get value by field name
Record.FieldNames(record)List of field names
Record.FieldValues(record)List of values
Record.HasFields(record, fields)Check if fields exist
Record.Combine(records)Merge multiple records
Record.SelectFields(record, fields)Keep only named fields
Record.RemoveFields(record, fields)Drop named fields

Type System

M TypeDescriptionExample Values
type textUnicode string"hello", ""
type number64-bit floating point3.14, -7, 0
Int64.Type64-bit integer42, -100
type logicalBooleantrue, false
type dateDate only (no time)#date(2024,1,15)
type timeTime only (no date)#time(14,30,0)
type datetimeDate + time#datetime(2024,1,15,14,30,0)
type datetimezoneDatetime + offsetWith timezone
type durationTime span#duration(1,2,30,0)
type nullNull/missing valuenull
type recordKey-value structure[Name="A", Age=30]
type tableTabular dataTable with typed columns
type listOrdered collection{1, 2, 3}
type binaryRaw bytesFile contents

Operators

OperatorTypesDescription
&text, list, recordConcatenation / merge
+, -, *, /number, durationArithmetic
=, <>anyEquality / inequality
<, >, <=, >=number, text, dateComparison
and, or, notlogicalBoolean logic
??anyCoalesce (null fallback) — M 2021+
?after field accessOptional field (null if missing)

Part of Data Analyst Toolkit

Chapter 3
🔒 Available in full product

Power Query M — Patterns & Best Practices Guide

Chapter 4
🔒 Available in full product

Power Query M — Getting Started in 5 Minutes

You’ve reached the end of the free preview

Get the full Excel Power Query Templates and unlock everything.

All Chapters

Get the complete guide with every chapter unlocked, including code samples, diagrams, and best practices.

Full Tool Suite

Access all interactive tools with complete data, all workload profiles, and the full scenario library.

Source Files

Downloadable source code, configuration files, and working examples from every chapter.

Lifetime Updates

Free updates for life. Every new chapter, tool, and improvement included.

Buy Now — $29 →
📦 Free sample included — download another copy for the full product.
Excel Power Query Templates v1.0.0 — Free Preview