Skip to content
Bronze 6 min read · Selection 3 practice problems ↓

select

A table often has fifty columns and you need five, or you need a new one worked out from the others. select does both in one step. This lesson shows the ways to name a column, how to compute and rename in the same call, and why choosing fewer columns makes Spark read less.

Step 1 · PySpark functions · Bronze · Read and select, lesson 2 of 5

In plain words first

Think of photocopying a spreadsheet but telling the copier which columns to keep, in which order, and to add a new column worked out from two others: "price times quantity, call it total". The original sheet is untouched; you get a new copy with only what you asked for.

That is select. A DataFrame never changes; every select gives you a new one with exactly the columns you listed.

What it does

A DataFrame is immutable, so select never changes the original. It builds a new DataFrame whose columns are the expressions you pass, in that order. Anything you do not list is dropped.

PySparkSpark SQL
employees.select("name", "dept")
SELECT name, dept FROM employees

Step by step

Here we keep two columns and compute a third: a 10% raise, renamed with alias.

Input

namedeptsalary
AshaEngineering72000
BenSales48000
ChitraEngineering95000

Output

namesalaryraised
Asha7200079200
Ben4800052800
Chitra95000104500

Every output row comes from exactly one input row: select never adds or removes rows, only columns.

  1. 1
    Spark resolves each name against the input schemaschema: The list of a DataFrame's columns and their types, such as order_id: long and city: string. Learn more →. A typo fails here, before any data is read, with an AnalysisException.
  2. 2
    Each expression is evaluated once per row. F.col("salary") * 1.1 is an expression, not a value: nothing is computed until an action runs.
  3. 3
    alias("raised") only renames the result. Without it the column would be called (salary * 1.1).

Run the example

PySparkSpark SQL

Input: employees

idnamedeptsalarymanager_id
1AshaEngineering72000nullnull: A missing or unknown value. Any comparison with null gives null, so filters treat it as false. Learn more →
2BenSales480001
3ChitraEngineering950001
4DevHR510001
5EshaSales500002
6Faridnull390002
from pyspark.sql import functions as F
result = employees.select(
    "name",
    "salary",
    F.round(F.col("salary") * 1.1).alias("raised"),
)
SELECT name,
       salary,
       ROUND(salary * 1.1) AS raised
FROM employees

Four ways to name a column

FormExampleUse it when
String"salary"You only need the column as is. Shortest and clearest.
F.colF.col("salary")You need an expression: arithmetic, comparisons, .alias, .cast. Works before the DataFrame variable exists.
Attributeemployees.salaryQuick exploration. Breaks for names with spaces or that clash with DataFrame methods, like count.
Itememployees["salary"]You must say which DataFrame a column comes from, typically after a join where both sides have the same name.
Tip: In production code, prefer F.col("x") for expressions and plain strings for pass-through columns. It reads well and never depends on a variable name.

select vs withColumn

Both add computed columns, but they scale differently. Every withColumn call adds one projection on top of the plan. Ten calls are fine. Hundreds, generated in a loop, make the plan so deep that Spark spends seconds or minutes just analysing it before any data moves, and can even fail with a StackOverflowError.

PySparkSpark SQL · Building many columns at once
numeric_cols = ["a", "b"]    # the columns to convert
cols = [F.col(c).cast("double").alias(c) for c in numeric_cols]
clean = df.select("id", *cols)
SELECT id,
       CAST(a AS DOUBLE) AS a,
       CAST(b AS DOUBLE) AS b
FROM df

One select with a list comprehension produces a single projection however many columns you add. Spark 3.3 also added withColumns({...}), which takes a dictionary and does the same.

Under the hood: column pruning Optional deep dive

When the source is a columnar format like ParquetParquet: A columnar file format: values of each column are stored together, so queries read only the columns they need. Learn more → or Delta, Spark only reads the columns that survive to the end of the plan. Selecting 5 columns from a 200-column table can cut the bytes read by 97%. You can see it in explain() as ReadSchema listing only the columns you used.

Part of explain() output

FileScan parquet [name#1,salary#3]
  ReadSchema: struct<name:string,salary:int>

This is why select("*") early in a pipeline is not free: if you keep every column until the end, Spark has to read every column.

Common mistakes

  • Forgetting alias on a computed column — The column gets a generated name like (salary * 1.1), which is awkward to reference later and breaks writes to tables with fixed column names.
  • Ambiguous columns after a join — If both sides have id, select("id") fails with "Reference id is ambiguous". Use a["id"], or join on a list of names (on=["id"]) so Spark keeps one copy.
  • Mixing up select and filter — select(F.col("salary") > 50000) returns one boolean column. It does not remove rows; that is filter.

Key takeaways

  • select returns a new DataFrame with only the columns you list; rows are unchanged.
  • Use alias to name computed columns.
  • Prefer one select over long loops of withColumn.
  • Selecting fewer columns lets Spark read fewer columns from Parquet and Delta.

Interview prep

THE QUESTION

"You need to cast 300 columns to double. How do you write it?"

Use one select with a list comprehension (or withColumns), not 300 withColumn calls in a loop. Explain why: each withColumn adds a projection, and a very deep plan is slow to analyse. Mentioning column pruning as a reason to select early is a bonus.

Avoid: a for loop of withColumn calls "because it is readable". It works on small schemas and makes planning painfully slow on wide ones.

Follow-ups · answer out loud, then open

Follow-up"How do you select all columns except two, and rename one, in one step?"
df.select([F.col(c).alias("customer_id") if c == "cust_id" else F.col(c) for c in df.columns if c not in ("tmp1", "tmp2")]). Or chain drop("tmp1", "tmp2").withColumnRenamed("cust_id", "customer_id") when readability matters more than one projection.
Scenario"A column name contains a dot, like 'price.usd'. select('price.usd') fails. Why, and how do you fix it?"
A dot means "field usd of struct price" to Spark. Quote it with backticks: F.col("`price.usd`"). Better, rename such columns once after reading, for example replacing dots and spaces with underscores.
Trap"select('name').filter('salary > 50000') fails because salary was not selected, right?"
Surprisingly, it often works: the analyzer can still find salary in the DataFrame before the select and push the filter below the projection. Do not rely on it; filter before selecting away the column so the code is clear and portable.

Check yourself

3 questions

What does employees.select(F.col("salary") > 50000) return?

Show the answer

One boolean column, with one row per employee. select evaluates the expression for every row and returns it as a column. Removing rows is filter's job.

Why can 500 chained withColumn calls be slow before any data is read?

Show the answer

Each call adds a projection, and analysing a very deep plan is expensive. withColumn is lazy and does not scan data, but each call adds a layer to the logical plan. Very deep plans take a long time to analyse and optimise.

You select 4 columns from a 120-column Parquet table. How many columns does Spark read from disk?

Show the answer

Only the 4 that are used. Column pruning pushes the projection into the Parquet scan, so only the referenced columns are read.

Practise this

Problems that use select, graded on hidden tests

See all 47 problems →

Keep going

Up next · Read and select · lesson 3 of 5 · 5 min read
filter / where
Keep the rows that match a condition, and the null and operator traps that silently drop data.

Related lessons

Previous: Reading and writing data

Primary sources: DataFrame.select · SELECT (Spark SQL)