Lesson 5 of 9 Data Engineering Practices

Writing Efficient Code and SQL for Data Engineering

This lesson explains the languages data engineers use on AWS and how the efficiency of their code directly affects the cost and speed of pipelines in the cloud.

Learning outcomes

After completing this lesson, you will be able to:

  • Identify where Python and SQL are used.
  • Write efficient processing code that filters early.
  • Apply common SQL techniques such as joins and window functions.

Languages

A data engineer on AWS works mainly in two languages. Python is used for PySpark jobs, for automation with the boto3 SDK, and for smaller transformations with pandas and the AWS SDK for pandas. SQL is used to query and transform data in Athena, Redshift and Spark SQL. Scala and Java appear in Spark and Flink applications, and shell scripts in Bash or PowerShell automate operational tasks. The following table summarises the languages.

LanguageUsed for
PythonPySpark, boto3, pandas, AWS SDK for pandas
SQLAthena, Redshift, Spark SQL
Scala and JavaSpark and Flink
Bash or PowerShellAutomation scripts
Match the pairs

Languages

Exam skills 1.4.3

Match each task with the language usually used.

Log in to try this activity Interactive activities are free with an account.

Writing efficient code

In data processing, inefficient code costs money directly, because jobs are billed for the compute time they use. The most effective practice is to filter rows and select columns early, so every later step processes less data; with columnar formats, early column selection also means less data is read at all.

In Spark, collect() and conversion of a large DataFrame to pandas bring all the data onto the single driver node, which loses the benefit of parallel processing and can exhaust the driver's memory. Built-in, vectorised functions should be preferred to row-by-row Python user-defined functions, which are much slower because each row passes between the JVM and Python. Outside Spark, reusing connections and clients and processing records in batches rather than one at a time have a similar effect.

The following diagram compares where the work runs before and after the rewrite.

Why collect() fails. Collecting the customer IDs moves the whole dataset onto the single driver, where a Python loop processes it row by row until the driver runs out of memory. Keeping the work in DataFrame operations lets every executor process its own partitions in parallel.
Executor counts are illustrative.

SQL skills

SQL remains the most common language of data engineering, used in Athena, Redshift, Spark SQL and Glue. A few techniques appear again and again. Each type of join, inner, left, right, full and cross, has a different effect on the number of rows returned, and an unexpected increase in row count after a join usually means duplicate keys on one side.

Window functions calculate across related rows, such as rankings and running totals, and ROW_NUMBER() partitioned by a key and ordered by a timestamp is the standard way to keep only the latest record per key when removing duplicates. Common table expressions, written with WITH, break complex queries into named, readable steps. MERGE performs upserts, updating existing rows and inserting new ones, in Amazon Redshift and in Apache Iceberg tables.

Match the pairs

SQL techniques

Exam skills 1.4.3 · 3.2.3

Match each requirement with the SQL technique.

Log in to try this activity Interactive activities are free with an account.
Worked example

A Spark job that collects to the driver

A PySpark job fails with an out-of-memory error on the driver. The code builds a list of all customer IDs with collect() and loops over it in Python. The following table pairs each problem with a better approach.

ProblemBetter approach
collect() pulls the whole dataset onto one machineKeep the work in DataFrame operations that run on executors
A Python loop over rowsVectorised DataFrame operations or SQL
A Python UDF for a simple calculationA built-in function
Repeatedly reading the same intermediate resultCache it once

Distributed engines are fast because work is spread across executors; anything that brings all data to the driver throws that away. The rewritten job runs in minutes on the same workers.

Check yourself

Why prefer built-in Spark functions to row-by-row Python UDFs?

Show answer

Built-in functions run inside Spark's optimised engine, while Python UDFs move every row to Python and back, which is much slower.

Exam Tips

Remember for the exam

  • Filter and project early to reduce the data each step processes.
  • Avoid collect() on large datasets, because it pulls everything to the driver.
  • Prefer built-in functions to row-by-row Python UDFs.
  • Deduplicate with ROW_NUMBER() over the key, keeping the latest row.
  • Use MERGE for upserts into Redshift and Iceberg tables.