Daily DAX : Day 395 SUBSTITUTEWITHINDEX

Power BI DAX: SUBSTITUTEWITHINDEX Advanced

Overview

The SUBSTITUTEWITHINDEX function is a powerful text manipulation function in Power BI DAX, introduced to efficiently replace portions of a string using an index-based lookup table.

It allows you to perform multiple, dynamic substitutions in a single operation — far more efficiently than nested SUBSTITUTE functions.

Syntax

SUBSTITUTEWITHINDEX (
    <expression>,
    <search_table>,
    <index_column>,
    <replacement_column>
    [, <occurrence>]
)
  • <expression>: The original text string to modify.
  • <search_table>: A table containing search and replacement values.
  • <index_column>: Column in the table with values to find in the expression.
  • <replacement_column>: Column with replacement values.
  • <occurrence> (Optional): Specifies which occurrence to replace (1 = first, 2 = second, etc.).

Use Case: Dynamic Product Code Translation

Imagine you have product codes like P001, P002 embedded in descriptions, and you want to replace them with full product names dynamically.

Step 1: Create a Mapping Table

Code (Index) ProductName (Replacement)
P001Laptop Pro 15"
P002Wireless Mouse
P003USB-C Hub

Step 2: Use SUBSTITUTEWITHINDEX

Translated Description = 
SUBSTITUTEWITHINDEX(
    Products[RawDescription],
    ProductMapping,
    ProductMapping[Code],
    ProductMapping[ProductName]
)

Result Example

Input: "Order includes P001 and P003"

Output: "Order includes Laptop Pro 15" and USB-C Hub"

Advanced Use Case: Multi-Occurrence Control

Use the optional occurrence parameter to replace only specific instances:

Replace First Only = 
SUBSTITUTEWITHINDEX(
    [Text],
    LookupTable,
    LookupTable[Find],
    LookupTable[Replace],
    1  // Only replace first match per row
)

Benefits vs Nested SUBSTITUTE

Why use SUBSTITUTEWITHINDEX?

  • Scalable: Add new mappings without changing DAX.
  • Performance: Faster than 10+ nested SUBSTITUTE() calls.
  • Maintainable: Centralize replacements in a table.
  • Dynamic: Works with filtered or related tables.

Limitations & Tips

  • Search is case-sensitive.
  • Requires a table — not compatible with scalar lists.
  • Use TRIM and UPPER/LOWER for case-insensitive matching.
  • Best for structured replacements (codes, IDs, abbreviations).


Comments

Popular posts from this blog

Daily DAX : Day 131 SELECTEDMEASURE

Daily DAX : Day 446 INFO.CSDLMETADATA

Daily DAX : Day 453 ENDOFWEEK