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
On this page
Show code in
Every code block on the page follows this.
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.
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
| name | dept | salary |
|---|---|---|
| Asha | Engineering | 72000 |
| Ben | Sales | 48000 |
| Chitra | Engineering | 95000 |
Output
| name | salary | raised |
|---|---|---|
| Asha | 72000 | 79200 |
| Ben | 48000 | 52800 |
| Chitra | 95000 | 104500 |
Every output row comes from exactly one input row: select never adds or removes rows, only columns.
- 1Spark 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. - 2Each expression is evaluated once per row.
F.col("salary") * 1.1is an expression, not a value: nothing is computed until an action runs. - 3
alias("raised")only renames the result. Without it the column would be called(salary * 1.1).
Run the example
Input: employees
| id | name | dept | salary | manager_id |
|---|---|---|---|---|
| 1 | Asha | Engineering | 72000 | nullnull: A missing or unknown value. Any comparison with null gives null, so filters treat it as false. Learn more → |
| 2 | Ben | Sales | 48000 | 1 |
| 3 | Chitra | Engineering | 95000 | 1 |
| 4 | Dev | HR | 51000 | 1 |
| 5 | Esha | Sales | 50000 | 2 |
| 6 | Farid | null | 39000 | 2 |
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
| Form | Example | Use it when |
|---|---|---|
| String | "salary" | You only need the column as is. Shortest and clearest. |
| F.col | F.col("salary") | You need an expression: arithmetic, comparisons, .alias, .cast. Works before the DataFrame variable exists. |
| Attribute | employees.salary | Quick exploration. Breaks for names with spaces or that clash with DataFrame methods, like count. |
| Item | employees["salary"] | You must say which DataFrame a column comes from, typically after a join where both sides have the same name. |
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.
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". Usea["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 isfilter.
Key takeaways
selectreturns a new DataFrame with only the columns you list; rows are unchanged.- Use
aliasto name computed columns. - Prefer one
selectover long loops ofwithColumn. - 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?"
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?"
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?"
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 questionsWhat 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
- Filter High EarnersFiltering & Selection Easy
- Distinct User ActionsFiltering & Selection Easy
- Build a Price ListFiltering & Selection Easy
Keep going
Up next · Read and select · lesson 3 of 5 · 5 min readfilter / 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)