Select specific columns in Spark
How Spark's select works for keeping specific columns: what it changes, common syntax, awkward column names, exporting to delimited files, and when a simpler tool fits better.
Selecting columns is one of the most common operations in Apache Spark: you have a wide DataFrame and need only a few fields for a report, a join or an export. This review covers what column selection actually does, the main ways to express it, where it can surprise you, and when a lighter tool is the better choice. No benchmarks or version-specific tests were available for this article, so performance and compatibility points are stated as documented behavior or general principles, not measured results.
What column selection changes and what it does not
In Spark, select is a projection. It returns a new DataFrame containing only the columns or expressions you list, in the order you list them. The original DataFrame is not modified, because DataFrames are immutable. In Spark terminology, select is a transformation, meaning it is lazy: nothing is read or computed until an action such as show, count, collect or a write is called.
The word transformation here does not mean the text itself is altered. Selecting a column passes its values through unchanged: no characters are reversed, restyled or substituted, and data types stay the same. Values change only if you deliberately wrap a column in an expression, such as a cast, a string function or arithmetic. Column names change only if you rename them, for example with alias.
Common ways to select columns
The PySpark API accepts column names as strings, column objects, or a list of either. These forms are interchangeable for plain columns; column objects become useful once you need expressions or renaming.
from pyspark.sql.functions import col
# By name
df.select("customer_id", "order_date", "total")
# From a Python list
wanted = ["customer_id", "order_date", "total"]
df.select(wanted)
# With column objects, renaming and an expression
df.select(
col("customer_id"),
col("order_date").alias("date"),
(col("total") * 1.1).alias("total_with_fee"),
)
# SQL-style expressions as strings
df.selectExpr("customer_id", "CAST(total AS INT) AS total_int")
The same projection can be written in Scala or in Spark SQL. The choice is mostly about which interface the rest of your pipeline uses.
// Scala
import org.apache.spark.sql.functions.col
df.select(col("customer_id"), col("order_date"), col("total"))
-- Spark SQL
SELECT customer_id, order_date, total FROM orders
Selecting by pattern, position or exclusion
When the column list is long or follows a naming convention, build it from df.columns rather than typing names by hand. PySpark also offers colRegex for regular-expression matching against column names. To keep everything except a few columns, drop is usually clearer than listing the survivors.
# Columns whose names start with a prefix
df.select([c for c in df.columns if c.startswith("metric_")])
# First three columns by position
df.select(df.columns[:3])
# Regular expression on column names (pattern wrapped in backticks)
df.select(df.colRegex("`^metric_.*`"))
# Everything except two columns
df.drop("internal_notes", "raw_payload")
Selection by position depends on the current column order, which can shift if an upstream schema changes. Name-based or pattern-based selection is more robust for pipelines that run repeatedly.
Pitfalls that affect correctness
- Column names containing dots or spaces: in a string reference, a dot is read as access into a nested struct field. Wrap such names in backticks, for example df.select("event.type"), to refer to a top-level column literally named event.type.
- Duplicate names: selecting the same column twice, or selecting columns with the same name from both sides of a join, produces duplicate column names. Later references to that name can fail as ambiguous, so rename with alias before continuing.
- Missing columns: a name that does not exist raises an analysis error when the plan is resolved. This usually surfaces early, but if column lists are generated dynamically, check them against df.columns first.
- Case sensitivity: Spark resolves column names case-insensitively by default, controlled by a configuration setting. Code that relies on case to distinguish columns can behave differently if that setting is changed.
- Nested data: selecting a struct column keeps the whole struct. To pull out individual fields as top-level columns, select them explicitly, such as col("address.city").
Performance: when selecting early helps
Spark's query optimizer can push a projection down to the data source, a technique known as column pruning. With columnar formats such as Parquet and ORC, this lets Spark avoid reading columns you never use. With row-oriented text formats such as CSV and JSON, every line still has to be read from storage, so selecting fewer columns reduces downstream work but not the volume of input read. The size of any gain depends on your data, file format and cluster; no measurements were available for this review, so check the physical plan with df.explain() to confirm that pruning is happening in your case.
Will the result stay usable when exported as delimited text?
For column selection, usability after sharing is mainly about the files you write. A few documented behaviors matter when the output is a CSV or other delimited file:
- Column order in the output follows the order in your select call, which makes select the natural place to fix the layout expected by downstream tools.
- Headers are not written by default; pass the header option if consumers need column names.
- The CSV writer cannot write struct, array or map columns directly. Flatten or convert them, for example with explicit field selection or a to_json expression, before writing.
- Values that contain the delimiter, quotes or line breaks are quoted by the writer, but the receiving tool must interpret quoting the same way. Test with a sample in the actual destination rather than assuming compatibility.
- Spark writes a directory of part files, not a single file. Reducing to one partition produces one file but forces all data through a single task, which is only reasonable for small outputs.
(df.select("customer_id", "order_date", "total")
.write
.option("header", True)
.mode("overwrite")
.csv("output/orders_subset"))
Concerns such as copy-and-paste rendering, screen reader behavior or reading order apply to styled or rearranged text, not to Spark column selection, because the selected values are stored unchanged. Accessibility of the final output depends on whatever tool presents it, which falls outside what this review can assess.
Is Spark column selection the right tool?
If your data already lives in Spark, select is the standard way to keep specific columns: it is declarative, preserves values and types, lets you rename and reorder in one step, and can reduce I/O on columnar formats. The decisive tradeoff is overhead. Spark brings session startup, cluster or local resource configuration, and multi-file output, which is unnecessary for a small, one-off task.
For a single delimited file that fits comfortably on one machine, a command-line utility, a spreadsheet or a small script in a general-purpose language is often simpler and produces a single plain-text file directly. Choose Spark when the data is large, already part of a Spark pipeline, stored in a columnar format, or needs to be combined with other distributed transformations.
Gaps in this review
No supplied evidence covered specific Spark versions, benchmark results or tests against particular destination tools. Behavior described here reflects long-standing documented Spark APIs; confirm details such as colRegex syntax, writer options and case-sensitivity defaults against the documentation for the Spark version you run.