Referencing a column — the 6 ways
Before you can transform a column you have to name one, and Spark gives you six syntaxes that all produce the same Column object. They're interchangeable — teams pick one for consistency. Knowing all six means you can read anyone's code.
col(colName: String): Column
column(colName: String): Column // identical to col
$"colName": Column // needs import spark.implicits._
'colName: Column // Scala Symbol, same result
df("colName"): Column // bound to a specific DataFrame
expr("colName + 1"): Column // parses a SQL expression string1. col("...") — the portable default
col (and its twin column) takes a column name as a string. It needs no DataFrame reference, so it's the safest choice in reusable helper functions:
import org.apache.spark.sql.functions.col
people.select(col("name"), col("country")).show()2. $"..." — the idiomatic shorthand
With import spark.implicits._ in scope, $"name" is the community-favourite shorthand for col("name"). It also unlocks operators like $"age" + 1 and $"age" > 30:
people.select($"name", ($"age" + 1).as("age_next_year")).show()3. df("...") — disambiguate after a join
When two DataFrames both have an id column, col("id") is ambiguous. people("id") binds the reference to a specific DataFrame — the one clean way to resolve it:
people.join(orders, people("id") === orders("user_id"))
.select(people("name"), orders("product"))
.show()4. expr("...") — a SQL string as a Column
expr parses a SQL expression string into a Column — handy when the logic is easier to read as SQL, or built dynamically at runtime:
import org.apache.spark.sql.functions.expr
people.select(
expr("name"),
expr("CASE WHEN age >= 30 THEN 'senior' ELSE 'junior' END AS tier")
).show()'name (a Scala Symbol) also works and reads cleanly, but is deprecated in newer Spark/Scala combos — prefer $"name" or col. And never mix a bare string like "name" where a Column is required; only some methods (e.g. select, drop) accept both.