๐ SELECT, Aliases & Sorting
SELECT is the statement you will write more than any other. In this tutorial you will learn how to pick columns, calculate new ones, rename them, remove duplicate rows, and sort the result exactly the way you want.
1. Sample Data
All examples use the employees view from the Introduction to Spark SQL. Run this first:
CREATE OR REPLACE TEMP VIEW employees AS
SELECT * FROM VALUES
(1, 'Asha', 'Engineering', 95000, DATE'2019-03-15', NULL, 'Bengaluru'),
(2, 'Ben', 'Engineering', 82000, DATE'2020-07-01', 1, 'Pune'),
(3, 'Chen', 'Sales', 60000, DATE'2021-01-10', 1, 'Mumbai'),
(4, 'Divya', 'Sales', 65000, DATE'2018-11-23', 3, 'Mumbai'),
(5, 'Elena', 'Marketing', 58000, DATE'2022-05-30', 1, NULL),
(6, 'Farid', 'Engineering', 82000, DATE'2023-02-14', 2, 'Bengaluru'),
(7, 'Grace', NULL, 45000, DATE'2024-01-08', NULL, 'Delhi')
AS employees(emp_id, name, dept, salary, hire_date, manager_id, city)
2. Selecting Specific Columns
SELECT * returns every column, which is handy for a quick look. In real queries, list only the columns you need:
SELECT name, dept, salary
FROM employees
ORDER BY emp_id
+-----+-----------+------+
|name |dept |salary|
+-----+-----------+------+
|Asha |Engineering|95000 |
|Ben |Engineering|82000 |
|Chen |Sales |60000 |
|Divya|Sales |65000 |
|Elena|Marketing |58000 |
|Farid|Engineering|82000 |
|Grace|NULL |45000 |
+-----+-----------+------+
The columns come back in the order you list them, not the order they have in the table.
Why it matters: Spark stores most data in columnar formats such as Parquet. When you select three columns, Spark reads only those three from disk. On a wide table with hundreds of columns,
SELECT *can be many times slower than a query that names its columns.
3. Calculated Columns
A SELECT list can hold any expression, not just column names. Spark computes it for every row:
SELECT name,
salary,
salary * 1.10 AS salary_after_raise,
ROUND(salary / 12, 2) AS monthly_salary,
upper(name) AS name_upper,
concat(name, ' (', dept, ')') AS label
FROM employees
ORDER BY emp_id
+-----+------+------------------+--------------+----------+-------------------+
|name |salary|salary_after_raise|monthly_salary|name_upper|label |
+-----+------+------------------+--------------+----------+-------------------+
|Asha |95000 |104500.00 |7916.67 |ASHA |Asha (Engineering) |
|Ben |82000 |90200.00 |6833.33 |BEN |Ben (Engineering) |
|Chen |60000 |66000.00 |5000.0 |CHEN |Chen (Sales) |
|Divya|65000 |71500.00 |5416.67 |DIVYA |Divya (Sales) |
|Elena|58000 |63800.00 |4833.33 |ELENA |Elena (Marketing) |
|Farid|82000 |90200.00 |6833.33 |FARID |Farid (Engineering)|
|Grace|45000 |49500.00 |3750.0 |GRACE |NULL |
+-----+------+------------------+--------------+----------+-------------------+
A few things to notice:
salary / 12is not integer division. In Spark SQL,/always returns a fractional result, soROUND(..., 2)keeps it tidy.concat()returnsNULLif any input isNULL. That is why Grace'slabelisNULL: herdeptis unknown. The Handling NULLs tutorial shows how to fix this.
4. Aliases and Backticks
AS renames a column in the output. The keyword AS is optional, but writing it makes queries easier to read.
If a name contains spaces or special characters, wrap it in backticks:
SELECT name AS employee,
salary AS `annual salary`,
hire_date hired_on
FROM employees
ORDER BY emp_id
LIMIT 3
+--------+-------------+----------+
|employee|annual salary|hired_on |
+--------+-------------+----------+
|Asha |95000 |2019-03-15|
|Ben |82000 |2020-07-01|
|Chen |60000 |2021-01-10|
+--------+-------------+----------+
Backticks also let you use a column whose name clashes with a SQL keyword, such as a column called order or date.
Common mistake: Using double or single quotes for a column name. In Spark SQL,
'annual salary'and"annual salary"are both string values, not names.SELECT 'name' FROM employeesreturns the wordnameseven times. Use backticks for names.
5. Removing Duplicates with DISTINCT
DISTINCT keeps one copy of each unique row in the result:
SELECT DISTINCT dept
FROM employees
ORDER BY dept
+-----------+
|dept |
+-----------+
|NULL |
|Engineering|
|Marketing |
|Sales |
+-----------+
Three departments plus NULL: DISTINCT treats all NULL values as equal, so they collapse into one row.
With several columns, DISTINCT looks at the combination of values:
SELECT DISTINCT dept, city
FROM employees
ORDER BY dept, city
+-----------+---------+
|dept |city |
+-----------+---------+
|NULL |Delhi |
|Engineering|Bengaluru|
|Engineering|Pune |
|Marketing |NULL |
|Sales |Mumbai |
+-----------+---------+
Asha and Farid are both in Engineering in Bengaluru, so that pair appears once. Ben is in Engineering in Pune, a different combination, so it gets its own row.
Interview tip:
DISTINCTapplies to the whole row, never to just the first column.SELECT DISTINCT dept, citydoes not mean "distinct departments, plus their city".
6. Sorting with ORDER BY
ORDER BY sorts the result. The default direction is ascending (ASC); add DESC for descending:
SELECT name, salary
FROM employees
ORDER BY salary DESC
+-----+------+
|name |salary|
+-----+------+
|Asha |95000 |
|Ben |82000 |
|Farid|82000 |
|Divya|65000 |
|Chen |60000 |
|Elena|58000 |
|Grace|45000 |
+-----+------+
Ben and Farid both earn 82,000. When values tie, Spark does not promise which row comes first, and the order can change between runs. Add a second sort column to break ties:
SELECT name, dept, salary
FROM employees
ORDER BY salary DESC, name ASC
+-----+-----------+------+
|name |dept |salary|
+-----+-----------+------+
|Asha |Engineering|95000 |
|Ben |Engineering|82000 |
|Farid|Engineering|82000 |
|Divya|Sales |65000 |
|Chen |Sales |60000 |
|Elena|Marketing |58000 |
|Grace|NULL |45000 |
+-----+-----------+------+
Now the ties are broken by name, so Ben always comes before Farid. Each column in ORDER BY has its own direction.
Common mistake: Relying on the order of rows without
ORDER BY. Spark reads data in parallel, so a query withoutORDER BYcan return rows in any order. If order matters, always sort.
7. Where Do NULLs Go When Sorting?
Spark puts NULL values first when sorting ascending and last when sorting descending:
SELECT name, city
FROM employees
ORDER BY city
+-----+---------+
|name |city |
+-----+---------+
|Elena|NULL |
|Asha |Bengaluru|
|Farid|Bengaluru|
|Grace|Delhi |
|Chen |Mumbai |
|Divya|Mumbai |
|Ben |Pune |
+-----+---------+
You can override this with NULLS FIRST or NULLS LAST:
SELECT name, city
FROM employees
ORDER BY city ASC NULLS LAST
+-----+---------+
|name |city |
+-----+---------+
|Asha |Bengaluru|
|Farid|Bengaluru|
|Grace|Delhi |
|Chen |Mumbai |
|Divya|Mumbai |
|Ben |Pune |
|Elena|NULL |
+-----+---------+
Elena, whose city is unknown, moved from the top to the bottom. Other databases make different choices here (PostgreSQL puts NULL last when ascending), so write NULLS FIRST or NULLS LAST explicitly when it matters.
8. Limiting Rows with LIMIT
LIMIT n returns at most n rows. Combined with ORDER BY, it answers "top N" questions:
SELECT name, salary
FROM employees
ORDER BY salary DESC, name
LIMIT 3
+-----+------+
|name |salary|
+-----+------+
|Asha |95000 |
|Ben |82000 |
|Farid|82000 |
+-----+------+
Without ORDER BY, LIMIT returns some n rows, not the first or the best. That is fine for a quick peek at the data, but never for a report.
9. Sorting by Alias or Position
Because ORDER BY runs after SELECT, it can use the aliases you defined:
SELECT name, salary * 1.10 AS new_salary
FROM employees
ORDER BY new_salary DESC, name
LIMIT 3
+-----+----------+
|name |new_salary|
+-----+----------+
|Asha |104500.00 |
|Ben |90200.00 |
|Farid|90200.00 |
+-----+----------+
You can also sort by the column's position in the SELECT list. ORDER BY 2 DESC means "sort by the second column":
SELECT name, salary
FROM employees
ORDER BY 2 DESC, 1
LIMIT 3
+-----+------+
|name |salary|
+-----+------+
|Asha |95000 |
|Ben |82000 |
|Farid|82000 |
+-----+------+
Positions are quick to type but easy to break: if someone adds a column to the SELECT list later, the sort silently changes. Prefer names in code you will keep.
10. Converting Types with CAST
CAST(value AS type) converts a value to another type. You also saw typed literals like DATE'2024-01-08', which create a value of a specific type directly:
SELECT CAST('42' AS INT) AS text_to_int,
CAST(3.9 AS INT) AS decimal_to_int,
CAST(salary AS STRING) AS salary_text,
CAST('2024-01-08' AS DATE) AS text_to_date,
typeof(DATE'2024-01-08') AS literal_type
FROM employees
WHERE emp_id = 1
+-----------+--------------+-----------+------------+------------+
|text_to_int|decimal_to_int|salary_text|text_to_date|literal_type|
+-----------+--------------+-----------+------------+------------+
|42 |3 |95000 |2024-01-08 |date |
+-----------+--------------+-----------+------------+------------+
typeof()tells you the type of any expression, which is useful when a result looks wrong.- Casting
3.9toINTdrops the fraction instead of rounding. UseROUND()first if you want 4.
What happens when a value cannot be converted?
SELECT CAST('abc' AS INT) AS bad_number
+----------+
|bad_number|
+----------+
|NULL |
+----------+
In Spark 3.5 (with the default settings), an impossible cast quietly returns NULL. With ANSI mode turned on, which is the default in Spark 4.0 and Databricks SQL, the same query raises an error instead. If you want NULL in both cases, use try_cast('abc' AS INT).
11. "All Columns Except One" Is Not Available
Some databases let you write SELECT * EXCEPT (city) to drop a column. Spark 3.5 does not support this syntax:
SELECT * EXCEPT (city) FROM employees
[PARSE_SYNTAX_ERROR] Syntax error at or near 'city'.(line 1, pos 17)
In Spark 3.5, list the columns you want instead. In PySpark, you can also use the DataFrame API: spark.table("employees").drop("city").
12. Try It in the Online Compiler
Copy this into the PySpark Online Compiler:
from pyspark.sql import SparkSession
spark = SparkSession.builder.appName("Spark SQL Select").getOrCreate()
spark.sql("""
CREATE OR REPLACE TEMP VIEW employees AS
SELECT * FROM VALUES
(1, 'Asha', 'Engineering', 95000, DATE'2019-03-15', NULL, 'Bengaluru'),
(2, 'Ben', 'Engineering', 82000, DATE'2020-07-01', 1, 'Pune'),
(3, 'Chen', 'Sales', 60000, DATE'2021-01-10', 1, 'Mumbai'),
(4, 'Divya', 'Sales', 65000, DATE'2018-11-23', 3, 'Mumbai'),
(5, 'Elena', 'Marketing', 58000, DATE'2022-05-30', 1, NULL),
(6, 'Farid', 'Engineering', 82000, DATE'2023-02-14', 2, 'Bengaluru'),
(7, 'Grace', NULL, 45000, DATE'2024-01-08', NULL, 'Delhi')
AS employees(emp_id, name, dept, salary, hire_date, manager_id, city)
""")
# Calculated columns with aliases
spark.sql("""
SELECT name, salary, ROUND(salary / 12, 2) AS monthly_salary
FROM employees
ORDER BY emp_id
""").show(truncate=False)
# Unique department and city pairs
spark.sql("SELECT DISTINCT dept, city FROM employees ORDER BY dept, city").show(truncate=False)
# Top 3 earners, ties broken by name
spark.sql("""
SELECT name, city, salary
FROM employees
ORDER BY salary DESC, name
LIMIT 3
""").show(truncate=False)
Summary
- Name the columns you need instead of
SELECT *; Spark then reads less data. - Any expression can go in
SELECT. Give it a name withAS, and use backticks for names with spaces. - Quotes create strings, backticks refer to names.
DISTINCTremoves duplicate rows and treatsNULLvalues as equal.ORDER BYsorts; add a tiebreaker column so ties come back in a stable order.- Spark sorts
NULLfirst in ascending order and last in descending order. UseNULLS FIRST/NULLS LASTto be explicit. LIMITwithoutORDER BYreturns arbitrary rows.CASTconverts types; in Spark 3.5 a failed cast returnsNULL.
Next, you will learn how to keep only the rows you want with WHERE.