$ spark-sql -e "SELECT city, SUM(amount) FROM lake.orders GROUP BY city"
Spark SQL
Spark SQL is the module of Apache Spark that runs SQL queries and DataFrame code on a cluster. Whether you write spark.sql("SELECT ...") or df.groupBy("city").sum("amount") in Python, Scala, Java or R, both become the same logical plan, are optimized by the Catalyst optimizer, and execute as distributed tasks. Today it is the main way people use Spark, and the default batch engine for lakehouse ETL on Parquet, Iceberg and Delta Lake tables.
From query to tasks
$ df.filter(col('dt') == '2026-11-16').groupBy('city').sum('amount')
The Catalyst pipeline
- SQL text and DataFrame calls enter the same pipeline. There is no performance difference between them.
- The parser builds an unresolved logical plan: a tree of operators whose table and column names are not yet checked.
- The analyzer looks names up in the catalog (Hive Metastore, Unity, Glue, an Iceberg catalog) and fills in types. Typos fail here.
- The optimizer applies rules: push filters into the Parquet scan, prune unused columns, fold constants, and (with the cost-based optimizer and table statistics enabled) reorder joins.
- The physical planner picks operators, such as a broadcast hash join when one side is small. Whole-stage codegen fuses each stage into tight generated code.
- Stages run on executors, separated by shuffles. Adaptive Query Execution uses the real sizes seen at each shuffle to merge small partitions, switch to broadcast joins and split skewed ones.
Run EXPLAIN FORMATTED <query> or df.explain("formatted") to see these plans for your own queries, and the SQL tab of the Spark UI to see the executed plan with row counts.
Key features
- DataFrames everywhere. A DataFrame is a distributed table with a schema. Datasets add compile-time types but exist only in Scala and Java.
- Data sources. Parquet, ORC, JSON, CSV, Avro, JDBC, Kafka, plus table formats (Iceberg, Delta Lake, Hudi) through catalog plugins.
- Hive compatibility. Spark can use the Hive Metastore as its catalog, read Hive tables and run most HiveQL. The Spark Thrift Server exposes Spark SQL over JDBC.
- Structured Streaming uses the same DataFrame API and optimizer for streaming queries.
- Spark Connect (since 3.4) separates the client from the cluster over gRPC, so thin Python or Go clients can submit DataFrame plans remotely.
- Spark 4.0 (2025) turned on ANSI SQL mode by default (errors on overflow and invalid casts instead of silent nulls), added the
VARIANTtype for semi-structured data, SQL pipe syntax and SQL user-defined functions, and removed Mesos support.
Spark SQL vs Trino
| Spark SQL | Trino / Presto | |
|---|---|---|
| Built for | Large batch ETL, mixed SQL + code, ML pipelines | Interactive queries, federation across sources |
| Execution | Stages write shuffle files; failed tasks retry | Pipelined in memory; whole query restarts unless fault-tolerant mode is on |
| Startup latency | Seconds to start a job (less on a warm cluster) | Sub-second on an always-on cluster |
| Languages | SQL, Python, Scala, Java, R | SQL only |
Many platforms use both: Spark writes the tables, Trino serves the dashboards.
Performance tips
- Keep AQE on (default since Spark 3.2) and check skew handling before hand-tuning
spark.sql.shuffle.partitions. - Prefer built-in functions to Python UDFs. A Python UDF is a black box to Catalyst and moves data between the JVM and Python. If you need one, use pandas/Arrow UDFs.
- Filter on partition columns and keep files 100 MB to 1 GB.
- Cache only what you reuse, and unpersist it afterwards.
- Native execution engines (Databricks Photon, Apache Gluten with Velox, Apache DataFusion Comet) replace Spark’s JVM operators with vectorized C++ or Rust for large speedups on scans and aggregations.
Common mistakes
collect()ortoPandas()on a large DataFrame, pulling everything to the driver until it runs out of memory.- Joining on columns with different types (
stringvsbigint), which forces casts and can break pushdown. - Running
count()just to log progress; each one is a full job.
Learning Resources
- Spark SQL, DataFrames and Datasets Guide: official docs
- Spark SQL performance tuning: AQE, joins, caching
- Spark SQL: Relational Data Processing in Spark (SIGMOD 2015): the Catalyst paper
- Learning Spark (2nd ed.), Jules Damji et al.: chapters 4 to 7 on Spark SQL and DataFrames
- Spark: The Definitive Guide, Bill Chambers and Matei Zaharia
- A Deep Dive into Query Execution Engine of Spark SQL: Maryann Xue, video