Sub topic 2
DuckDB: An Embedded SQL Engine for Analytics
Assume you know Python imports, tabular data, and basic SQL. You should also understand rows, columns, and data types.
DuckDB: SQL Without a Separate Server
DuckDB is an embedded analytical database. It runs inside your Python process, so you do not need to start a database server. It can query local files such as Parquet directly.
DuckDB is a strong choice for interactive analysis and batch jobs that fit on one machine. It uses SQL, supports columnar data, and can avoid loading an entire file into a DataFrame.
import duckdb
result = duckdb.sql(
"SELECT region, sum(revenue) AS revenue "
"FROM 'sales.parquet' GROUP BY region"
).df()
print(result)Apache Spark: Distributed Processing
Apache Spark is a distributed processing engine. It divides data and work across multiple machines called executors. This makes Spark useful when one machine cannot process the data or when an organization already operates a Spark cluster.
Spark has more startup and operational cost than DuckDB. Operations are usually lazy: Spark builds a plan first, then runs it when an action such as show() or write is called.
from pyspark.sql import SparkSession, functions as F
spark = SparkSession.builder.appName("sales").getOrCreate()
result = (
spark.read.parquet("sales.parquet")
.groupBy("region")
.agg(F.sum("revenue").alias("revenue"))
)
result.show()
spark.stop()The Same Aggregation in Four Tools
This task filters positive revenue and sums it by region:
import pandas as pd
df = pd.read_parquet("sales.parquet", columns=["region", "revenue"])
print(df[df["revenue"] > 0].groupby("region", as_index=False)["revenue"].sum())import polars as pl
print(
pl.scan_parquet("sales.parquet")
.filter(pl.col("revenue") > 0)
.group_by("region")
.agg(pl.col("revenue").sum())
.collect()
)DuckDB expresses the same operation with WHERE and GROUP BY. Spark uses filter, groupBy, and agg. The output should match, but execution, memory use, and scheduling differ.
Lazy Evaluation and Optimization
Eager tools run each operation immediately. Lazy tools build a query plan. Before execution, the optimizer can remove unnecessary work, such as reading unused columns or filtering earlier.
import polars as pl
query = (
pl.scan_parquet("sales.parquet")
.filter(pl.col("revenue") > 0)
.select("region", "revenue")
)
print(query.explain())
print(query.collect())Exercise
Why might DuckDB be preferable to pandas for a Parquet aggregation?
Show answer
DuckDB can run SQL directly against the file and return only the aggregated result, avoiding a full in-memory DataFrame.