REPLACE: from Tableau to SQL

Replaces every literal occurrence of a substring. Below, 8 sample rows go through the calculation and through the SQL, and both return the same numbers.

Calculated field

REPLACE([label], 'birch', 'oak')

Sample data

labelquantityamountflag
cedar cedar 6512.8True
ORCHID-west66-7.6False
maple-east670null
willow north6825.3True
birch-birch694.9False
pine/south70-1.2null
ash719True
nullnullnullnull

The same calculation as SQL

SELECT replace(label,'birch','oak') AS result FROM input

Runs the example above.

Result

result
cedar cedar
ORCHID-west
maple-east
willow north
oak-oak
pine/south
ash
null

Same rows from the calculation and from the SQL in DuckDB.

Where a naive translation goes wrong

  • DuckDB regexp_replace without g changes only the first match.

    Naive SQL

    SELECT regexp_replace(label,'birch','oak') AS result FROM input
    result
    cedar cedar
    ORCHID-west
    maple-east
    willow north
    oak-birch
    pine/south
    ash
    null

    Matches the calculation

    SELECT replace(label,'birch','oak') AS result FROM input
    result
    cedar cedar
    ORCHID-west
    maple-east
    willow north
    oak-oak
    pine/south
    ash
    null

Signature

REPLACE(string, string, expression)