SparkSQL Project Report
SparkSQL Project Report
Aadhithiyan. B
Student Names : Arun Adhithiya. G
Danush. S
820423104002
Register Numbers : 820423104008
820423104018
Spark SQL – Hands-on Tryout | Anjalai Ammal Mahalingam Engineering College Page 1
ABSTRACT
Apache Spark is a powerful open-source distributed computing framework designed for large-scale data
processing. Spark SQL is a module within Apache Spark that enables structured data processing using
SQL-like queries. This project report presents a comprehensive hands-on exploration of Spark SQL using
PySpark — the Python API for Apache Spark — in a Google Colab / local Python environment. The
experiment involves creating a structured DataFrame representing student academic records with attributes
such as student ID, name, marks, grade, and department. SQL queries including SELECT, WHERE, GROUP
BY, ORDER BY, AVG, MAX, MIN, and COUNT are executed on this dataset to retrieve and analyse
information. Key objectives include understanding how Spark SQL integrates with the Spark ecosystem,
registering DataFrames as temporary SQL views, executing analytical queries, and observing the query
execution plan. The results demonstrate Spark SQL's ability to process structured data intuitively and
efficiently. The experiment concludes with a study of real-world applications, advantages, and limitations of
Spark SQL, providing students with a solid foundation for big data analytics.
Keywords : Apache Spark, Spark SQL, PySpark, DataFrame, Big Data, SQL Queries, Distributed Computing
Spark SQL – Hands-on Tryout | Anjalai Ammal Mahalingam Engineering College Page 2
1. INTRODUCTION TO APACHE SPARK AND SPARK SQL
Spark provides a unified platform for batch processing, real-time stream processing, machine learning
(MLlib), graph computation (GraphX), and structured data querying (Spark SQL). It supports APIs in Python
(PySpark), Scala, Java, and R.
Component Purpose
Spark Core Base engine – task scheduling, memory management, fault recovery
• Unified Data Access: Read data from JSON, CSV, Parquet, ORC, Avro, Hive tables, and JDBC
databases using one consistent API.
• Catalyst Optimiser: An advanced query optimiser that automatically rewrites and optimises SQL queries
for maximum performance.
• Tungsten Execution Engine: A memory and CPU-efficient execution engine that generates optimised
JVM bytecode.
• Interoperability: DataFrames can be converted to/from RDDs and used together with Spark's other
libraries.
• Schema Inference: Spark SQL can automatically detect the schema (column names and types) from
structured file formats.
■ Spark SQL uses a component called the Catalyst Optimiser to automatically choose the most efficient
query plan — similar to how traditional databases use query optimisers, but at a distributed scale.
Spark SQL – Hands-on Tryout | Anjalai Ammal Mahalingam Engineering College Page 3
2. OBJECTIVES OF THE EXPERIMENT
By the end of this hands-on experiment, students will be able to:
3. SYSTEM REQUIREMENTS
RAM 4 GB 8 GB or more
Spark SQL – Hands-on Tryout | Anjalai Ammal Mahalingam Engineering College Page 4
4. ARCHITECTURE OF SPARK SQL
Spark SQL follows a layered architecture that converts a user's SQL or DataFrame API call into an optimised
physical execution plan distributed across multiple machines. The diagram below illustrates the key layers.
USER INTERFACE LAYER SQL Queries | DataFrame API | Dataset API | HiveQL
CATALYST OPTIMISER Parse SQL → Logical Plan → Optimised Logical Plan → Physical Plan
SPARK CORE ENGINE Task Scheduling | DAG Execution | Fault Tolerance | In-memory Storage
Spark SQL – Hands-on Tryout | Anjalai Ammal Mahalingam Engineering College Page 5
5. METHODOLOGY / PROCEDURE
The experiment is divided into clearly defined steps. Follow the procedure sequentially to successfully
execute Spark SQL queries.
Spark SQL – Hands-on Tryout | Anjalai Ammal Mahalingam Engineering College Page 6
6. SAMPLE DATASET – STUDENT ACADEMIC RECORDS
A realistic student dataset is used for all experiments in this report. The dataset contains 15 student records
with the following attributes:
Spark SQL – Hands-on Tryout | Anjalai Ammal Mahalingam Engineering College Page 7
Table 6.2 – Complete Student Records Dataset
Spark SQL – Hands-on Tryout | Anjalai Ammal Mahalingam Engineering College Page 8
7. IMPLEMENTATION WITH PYSPARK CODE
■ Note: 'local[*]' tells Spark to run locally using all available CPU cores. In a production cluster, this would
be replaced with the cluster master URL.
Spark SQL – Hands-on Tryout | Anjalai Ammal Mahalingam Engineering College Page 9
StructField('cgpa', DoubleType(), False),
StructField('city', StringType(), False),
])
# ■■ Dataset
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
data = [
(101, 'Aravind Kumar', 'CSE', 6, 92, 'O', 9.4, 'Chennai'),
(102, 'Priya Lakshmi', 'ECE', 6, 85, 'A+', 8.7, 'Coimbatore'),
(103, 'Mohammed Rizwan', 'CSE', 6, 78, 'A', 8.1, 'Madurai'),
(104, 'Deepika Nair', 'MECH', 4, 65, 'B+', 7.2, 'Trichy'),
(105, 'Karthik Rajan', 'EEE', 6, 90, 'O', 9.2, 'Salem'),
(106, 'Sneha Pillai', 'CSE', 6, 88, 'A+', 8.9, 'Vellore'),
(107, 'Ramesh Babu', 'CIVIL', 4, 55, 'B', 6.8, 'Erode'),
(108, 'Anitha Devi', 'ECE', 6, 95, 'O', 9.6, 'Chennai'),
(109, 'Vishal Chandran', 'MECH', 4, 72, 'A', 7.8, 'Tirunelveli'),
(110, 'Kavitha Srinivas','CSE', 6, 83, 'A+', 8.5, 'Madurai'),
(111, 'Suresh Pandi', 'EEE', 4, 60, 'B+', 7.0, 'Dindigul'),
(112, 'Logesh Murugan', 'CSE', 6, 97, 'O', 9.8, 'Chennai'),
(113, 'Vijayalakshmi', 'CIVIL', 4, 48, 'C', 6.2, 'Thanjavur'),
(114, 'Dinesh Raj', 'ECE', 6, 81, 'A+', 8.3, 'Puducherry'),
(115, 'Keerthana Nair', 'MECH', 4, 70, 'A', 7.6, 'Coimbatore'),
]
# ■■ Create DataFrame ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
df = [Link](data, schema)
[Link]()
[Link](5)
Once registered, we can query this view using standard SQL syntax via [Link]('...'). The view exists only
for the duration of the SparkSession.
PySpark Code:
Spark SQL – Hands-on Tryout | Anjalai Ammal Mahalingam Engineering College Page 10
Explanation: This retrieves all 15 rows and all 8 columns from the students view. It is equivalent to a full
table scan.
Expected Output:
SELECT student_id, name, department, marks, grade FROM students WHERE marks > 80 ORDER
BY marks DESC;
PySpark Code:
Explanation: The WHERE clause filters out students with marks ≤ 80. ORDER BY marks DESC sorts the
results from highest to lowest score. 9 out of 15 students have marks above 80.
Expected Output:
Spark SQL – Hands-on Tryout | Anjalai Ammal Mahalingam Engineering College Page 11
Output 8.3 – Students with Marks > 80 (Sorted Descending)
GROUP BY department aggregates all rows belonging to the same department. AVG(), MAX(), MIN(), and
COUNT() are applied to each group independently. ROUND() formats the average to 2 decimal places.
CSE 5 87.60 97 78
ECE 3 87.00 95 81
EEE 2 75.00 90 60
MECH 3 69.00 72 65
CIVIL 2 51.50 55 48
Output 8.4 – Department-wise Statistics
Spark SQL – Hands-on Tryout | Anjalai Ammal Mahalingam Engineering College Page 12
8.6 Query 5 – Grade Distribution (HAVING clause)
# Query 5: Count of students per grade
result5 = [Link]('''
SELECT grade,
COUNT(*) AS student_count
FROM students
GROUP BY grade
HAVING COUNT(*) >= 1
ORDER BY student_count DESC
''')
[Link]()
O 4
A+ 4
A 3
B+ 2
B 1
C 1
Output 8.6 – Grade Distribution
Spark SQL – Hands-on Tryout | Anjalai Ammal Mahalingam Engineering College Page 13
.agg(
[Link]([Link]('cgpa'), 2).alias('avg_cgpa'),
[Link]('student_id').alias('count')
) \
.orderBy('avg_cgpa', ascending=False)
[Link]()
CSE 8.94 5
ECE 8.87 3
EEE 8.1 2
MECH 7.53 3
CIVIL 6.5 2
Output 8.8 – Average CGPA per Department (DataFrame API)
Vijayalakshmi 48 Fail
Output 8.9 – Students Categorised by Result
Spark SQL – Hands-on Tryout | Anjalai Ammal Mahalingam Engineering College Page 14
8.10 Viewing the Query Execution Plan
# View the physical execution plan
[Link]()
# View extended plan (parsed, analysed, optimised, physical)
[Link](extended=True)
The explain() output shows how Spark internally plans and executes the query. You can observe operations
like HashAggregate, Exchange (shuffle), Sort, and FileScan in the execution plan. This helps developers
understand performance bottlenecks and optimise queries.
Spark SQL – Hands-on Tryout | Anjalai Ammal Mahalingam Engineering College Page 15
9. RESULTS AND OBSERVATIONS
Query Records
Query Description Key Observation
No. Returned
Q7 Avg CGPA (DataFrame API) 5 CSE leads CGPA with 8.94 average
Spark SQL – Hands-on Tryout | Anjalai Ammal Mahalingam Engineering College Page 16
10. ADVANTAGES AND LIMITATIONS OF SPARK SQL
10.1 Advantages
• High Speed: Processes data in-memory, making it up to 100× faster than Hadoop MapReduce for iterative
computations.
• Familiar SQL Syntax: SQL developers can immediately use Spark SQL without learning a completely new
language or API.
• Unified API: Works seamlessly with other Spark modules (Streaming, MLlib, GraphX) within a single
application.
• Multiple Data Source Support: Natively reads CSV, JSON, Parquet, ORC, Avro, Hive, JDBC, and Delta
Lake.
• Catalyst Optimiser: Automatically rewrites and optimises queries, reducing developer effort for
performance tuning.
• Scalability: Scales from a single laptop to a cluster of thousands of nodes without code changes.
• Schema Evolution: Supports schema evolution with formats like Parquet and Delta Lake.
• Language Flexibility: Available in Python (PySpark), Scala, Java, and R.
• ANSI SQL Compliance: Supports standard SQL features including window functions, subqueries, CTEs,
and user-defined functions (UDFs).
• Open Source and Free: Apache-licensed, with a large active community and extensive documentation.
10.2 Limitations
• High Memory Requirement: In-memory processing requires substantial RAM. Memory-intensive jobs
may spill to disk, reducing performance.
• Not Ideal for Small Datasets: The overhead of setting up a SparkSession and distributing tasks is
unnecessary for datasets that fit in a single machine's memory.
• Complex Setup: Configuring a production Spark cluster (standalone, YARN, Kubernetes) requires
significant DevOps expertise.
• Latency: Spark is optimised for batch and micro-batch processing. For sub-second real-time queries,
dedicated systems like Apache Flink or Druid are preferred.
• Debugging Difficulty: Distributed execution makes it harder to debug errors compared to local
single-threaded programs.
• No Transactional Support: Standard Spark SQL does not support ACID transactions (though Delta Lake
and Iceberg add this capability).
• Limited UPDATE/DELETE: Direct UPDATE or DELETE SQL operations on DataFrames are not natively
supported without Delta Lake.
Spark SQL – Hands-on Tryout | Anjalai Ammal Mahalingam Engineering College Page 17
11. REAL-WORLD APPLICATIONS OF SPARK SQL
Amazon, Flipkart, and Alibaba use Spark SQL to analyse billions of transaction
1 E-Commerce Analytics records daily — computing product recommendations, sales trends, inventory
forecasts, and customer segmentation at scale.
Banks like HDFC, Axis, and global institutions use Spark SQL to query millions
2 Financial Fraud Detection of transactions in real time, identifying suspicious patterns, anomalies, and
fraudulent activities before they cause damage.
Telecom providers use Spark SQL to analyse call detail records (CDR), detect
5 Telecom Network Analytics network outages, monitor QoS metrics, and predict customer churn from usage
patterns.
Tech companies like Netflix and Uber use Spark SQL to query terabytes of
6 Log Analytics server log files daily, monitoring application performance, detecting errors, and
analysing system behaviour.
Smart city platforms and industrial IoT systems use Spark SQL to query sensor
7 IoT Data Processing streams from thousands of devices, computing aggregates like average
temperature, peak load, and anomaly detection.
Enterprises integrate Spark SQL with BI tools like Tableau, Power BI, and
8 Business Intelligence Looker through JDBC/ODBC connectors, enabling analysts to run SQL reports
over petabyte-scale data warehouses.
Table 11.1 – Real-World Applications of Spark SQL
Spark SQL – Hands-on Tryout | Anjalai Ammal Mahalingam Engineering College Page 18
12. CONCLUSION
This experiment successfully demonstrated the capabilities of Apache Spark SQL for structured data
processing using PySpark. Starting from the installation of PySpark and the creation of a SparkSession, we
progressed through defining a schema, loading a realistic student dataset, and registering it as a temporary
SQL view.
A total of eight diverse SQL queries were executed, covering fundamental operations such as SELECT,
WHERE-based filtering, GROUP BY with aggregate functions (AVG, COUNT, MAX, MIN), ORDER BY
sorting, LIMIT, HAVING, and conditional CASE WHEN logic. The same operations were also demonstrated
using the DataFrame API, confirming the interoperability of both programming styles within Spark SQL.
The experiment validated that Spark SQL provides a powerful, familiar, and highly scalable interface for big
data analytics. The Catalyst Optimiser automatically generated efficient execution plans, and lazy evaluation
ensured that computations were only triggered when an action (such as .show()) was called.
The study of query execution plans using .explain() provided insight into how Spark internally handles
distributed query processing, including hash aggregation, range partitioning, and adaptive query execution
(AQE).
In conclusion, Spark SQL is a foundational tool in the modern big data ecosystem. Mastering it equips
computer science engineers with the skills to build scalable data pipelines, analytics platforms, and machine
learning workflows that operate on datasets ranging from megabytes to petabytes.
Spark SQL – Hands-on Tryout | Anjalai Ammal Mahalingam Engineering College Page 19
13. VIVA QUESTIONS WITH ANSWERS
The following questions are commonly asked during viva examinations related to this experiment. Study them
carefully.
Q1. What is Apache Spark, and how is it different from Hadoop MapReduce?
Ans: Apache Spark is an open-source distributed computing framework that processes data primarily in
memory (RAM), making it significantly faster than Hadoop MapReduce, which reads and writes
intermediate data to HDFS disk at every step. Spark also provides a unified API for batch, streaming, SQL,
and machine learning workloads, whereas Hadoop MapReduce is limited to batch processing.
Q7. What is a temporary view in Spark SQL? How do you create one?
Ans: A temporary view is a named SQL alias for a DataFrame that exists only within the current
SparkSession. It allows SQL queries to reference the DataFrame by name. It is created using:
[Link]('view_name'). The view disappears when the SparkSession ends.
Spark SQL – Hands-on Tryout | Anjalai Ammal Mahalingam Engineering College Page 20
Ans: createOrReplaceTempView() creates a view visible only within the current SparkSession.
createGlobalTempView() creates a view that persists across multiple SparkSessions within the same
Spark application, accessible via the 'global_temp' database prefix (e.g., SELECT * FROM
global_temp.view_name).
Q10. Name four SQL aggregate functions supported by Spark SQL with examples.
Ans: AVG(marks) — computes the average marks of students. COUNT(*) — counts the total number of
rows. MAX(cgpa) — returns the highest CGPA value. MIN(marks) — returns the lowest marks.
SUM(marks) — returns the total sum of all marks values.
Q11. What is the purpose of the HAVING clause? How is it different from WHERE?
Ans: WHERE filters individual rows before grouping occurs. HAVING filters groups after GROUP BY has
aggregated the data. For example: WHERE marks > 80 filters individual students, whereas HAVING
COUNT(*) > 2 filters only those departments having more than 2 students.
Q12. What file formats does Spark SQL natively support for reading and writing data?
Ans: Spark SQL natively supports: CSV (comma-separated values), JSON (JavaScript Object Notation),
Parquet (columnar storage format — default in Spark), ORC (Optimised Row Columnar), Avro (row-based
binary format), Text files, Hive tables, JDBC/ODBC databases, and Delta Lake (with the delta package).
Q14. What is the difference between RDD, DataFrame, and Dataset in Spark?
Ans: RDD (Resilient Distributed Dataset) is the low-level, unstructured distributed collection with no
schema — type-safe in Scala/Java but verbose. DataFrame is a structured, tabular RDD with named
columns and schema, similar to a SQL table — available in all languages but not type-safe in Python.
Dataset combines the benefits of both — structured schema and compile-time type safety — but is only
available in Scala and Java, not Python.
Q15. How would you write the output of a Spark SQL query to a CSV file?
Ans: Use the write API: [Link]('overwrite').option('header', True).csv('/path/to/output/folder').
The mode can be 'overwrite', 'append', 'ignore', or 'errorIfExists'. Spark writes one CSV file per partition, so
coalesce(1) or repartition(1) can be used to produce a single file.
Spark SQL – Hands-on Tryout | Anjalai Ammal Mahalingam Engineering College Page 21
14. REFERENCES
[1] Apache Spark Official Documentation – [Link]
[2] Holden Karau, Andy Konwinski, Patrick Wendell, and Matei Zaharia, Learning Spark: Lightning-Fast Data
Analytics, 2nd ed., O'Reilly Media, 2020.
[3] Bill Chambers and Matei Zaharia, Spark: The Definitive Guide, O'Reilly Media, 2018.
[6] M. Zaharia et al., 'Apache Spark: A Unified Engine for Big Data Processing,' Communications of the
ACM, vol. 59, no. 11, pp. 56–65, Nov. 2016.
[7] Google Colab – [Link] (for running PySpark without local installation)
Spark SQL – Hands-on Tryout | Anjalai Ammal Mahalingam Engineering College Page 22