concat & concat_ws — joining strings
concat glues columns/values together end to end; concat_ws ("with separator") joins them with a delimiter and skips nulls. Both are imported from org.apache.spark.sql.functions.
def concat(exprs: Column*): Column def concat_ws(sep: String, exprs: Column*): Column // skips nulls
1. concat — end to end
Build a label like Wireless Mouse (Electronics) from two columns and literals:
import org.apache.spark.sql.functions.{concat, lit}
orders.select(
concat($"product", lit(" ("), $"category", lit(")")).as("label")
).show(3, false)2. concat_ws — with a separator
Far cleaner when you have a delimiter — no repeating the separator, and nulls are dropped automatically:
import org.apache.spark.sql.functions.concat_ws
orders.select(
concat_ws(" - ", $"product", $"category", $"status").as("summary")
).show(3, false)concat returns null if any argument is null, while concat_ws simply skips the null and keeps going. When joining columns that might be null, prefer concat_ws — or wrap args in coalesce first.