Unit 6 Cloud Pipelines Notes

Unit 6 — Cleaning and Transforming Data | DataSoSi
Cloud Data Pipelines · Unit 6 of 12 · Data Cleaning

Cleaning and Transforming Data

Use simple SQL inside Databricks to remove missing values, standardize inconsistent text, and turn a messy raw dataset into a clean, reliable output — ready for reporting.

Imagine receiving a handwritten list of 300 customer addresses — some in all capitals, some in lowercase, some with phone numbers missing entirely. Before you could mail anything, you would need to fix the formatting and remove the incomplete entries. That is exactly what data cleaning does, just automated: the rules run once and apply perfectly to every row, every time.
4 Sections
6 Hands-On Cells
Intro SQL — No Experience Needed
1 2 3 4 5 6 7 8 9 10 11 12

Learning Objectives

  • Explain what data cleaning is and why messy data leads to unreliable reports and business decisions
  • Identify the most common data quality problems — missing values, inconsistent formatting, and duplicate records
  • Create a dataset in Databricks and register it as a temporary SQL table
  • Write and run four SQL queries that view, filter, standardize, and combine cleaning operations
  • Explain in plain language what SELECT, WHERE, IS NOT NULL, and UPPER() each do
Four sections. Select individually or expand all.

In Unit 5 you loaded a dataset and inspected it. Now you are going to change it. Cleaning is the step where problems found during inspection are actually fixed — missing values removed, formatting standardized, inconsistencies corrected — so that the data is safe to use downstream.

Everyday Analogy — Sorting the Post

Picture the morning post arriving at a busy office. Some envelopes have no address. Some have the addressee’s name in all caps, some in lowercase, some with a middle initial — all referring to the same person. Before a receptionist can distribute anything, they sort out the unaddressable envelopes, standardize the name format, and remove duplicates. Data cleaning is this sorting process, applied to datasets instead of envelopes — automated so it happens in seconds rather than hours.

The Dataset That Needs Cleaning

The sales dataset you will work with this unit has three problems. Spotting these before writing a single query is the first habit of a good data practitioner.

Raw Data — Problems Present
Employee
Sales
Region
Alice
500
west
Bob
NULL
East
Charlie
450
north
Cleaned Data — Problems Resolved
Employee
Sales
Region
Alice
500
WEST
Bob’s row removed — missing sales value
Charlie
450
NORTH
ProblemWhat It IsWhy It Matters
NULL sales value Bob’s sales figure is missing — represented as NULL, meaning no value exists Any total or average calculated using this column will be wrong or will fail entirely
Inconsistent capitalisation “west” and “north” are lowercase while “East” is capitalised — all are the same type of value A filter for “West” would miss “west”. Regional reports would show three entries where only one should exist
No duplicates here, but… This dataset is small. Real files often contain duplicate rows from system exports or merges Duplicates inflate counts and totals — a record processed twice appears as two sales instead of one
What Is a Transformation?

A transformation is any operation that changes the structure or content of data to make it more useful. Transformations do not invent new information — they reshape or filter what already exists. Common examples in business pipelines include renaming columns to consistent labels, converting text to uppercase for uniform reporting, filtering out rows that fail a quality check, and calculating new values from existing ones.

SQL in Databricks

Databricks supports both Python and SQL in the same notebook — you can switch between them cell by cell. SQL (Structured Query Language) is the standard language for talking to data tables. It reads almost like plain English: “SELECT these columns FROM this table WHERE this condition is true.” You do not need to memorize SQL syntax — the four queries in this unit cover the most common cleaning operations used in real pipelines.

SQL queries look more intimidating than they are. Every query in this unit follows the same basic pattern: you say what you want to see, where you want to get it from, and optionally what condition the data must meet. That is the entire structure.

Everyday Analogy — Asking a Filing Clerk

Imagine asking a filing clerk: “Please bring me the name and salary columns from the employee file, but only for employees who have a salary on record, and write all the department names in capitals.” A SQL query says exactly the same thing to a database. SELECT = “bring me these columns.” FROM = “from this file.” WHERE = “but only the rows that match this condition.” UPPER() = “write this in capitals.” Once you see SQL as a conversation with a very literal assistant, it stops feeling like code.

The Four SQL Building Blocks Used in This Unit
SELECT Chooses which columns to show in the result. SELECT * means “show all columns.” SELECT employee, sales means “show only the employee and sales columns.”
FROM Tells the query which table to read from. In this unit the table is called sales_table — the temporary table you will create from the Python dataset.
WHERE Filters the rows. Only rows that meet the condition after WHERE are included in the result. It is the gatekeeper — rows that do not pass are excluded from the output entirely.
IS NOT NULL A condition used inside WHERE. NULL means a value is missing. WHERE sales IS NOT NULL means “only include rows where the sales column has a real value.”
UPPER() A function that converts text to uppercase. UPPER(region) returns “WEST” regardless of whether the original was “west”, “West”, or “WEST.” It enforces consistency without changing the underlying data.
AS Gives a column a new label in the output. UPPER(region) AS cleaned_region applies the function and calls the result “cleaned_region” in the output table.
SQL Does Not Change the Original Data

A SQL SELECT query reads data and returns a result — it does not modify the table it reads from. The original sales_table remains exactly as it was. This is an important safety property: you can run as many SELECT queries as you like without worrying about accidentally overwriting or corrupting your source data. Changes only happen when you explicitly write an output, which happens in Unit 7.

Create a new notebook named Unit6_Clean_Data in Databricks, set the language to Python, and attach it to your cluster. The first two cells are Python — they create the data and register it as a SQL table. Cells 3 through 6 use SQL to query and clean it.

Cell 1 — Create the Messy Dataset
Python Cell 1 — Raw Dataset with Problems
data = [
    [“Alice”, 500, “west”],
    [“Bob”, None, “East”],
    [“Charlie”, 450, “north”]
]

print(data)
Expected Output
[[‘Alice’, 500, ‘west’], [‘Bob’, None, ‘East’], [‘Charlie’, 450, ‘north’]]
What Is Happening Here

This is the raw dataset — exactly the kind of data that arrives from a real business system before any cleaning. Three problems are visible immediately: Bob’s sales value is None (Python’s way of representing a missing value — it becomes NULL in SQL), and the region values “west” and “north” are lowercase while “East” is capitalised. None of these problems would prevent the data from loading — they would only cause incorrect results if processed without being fixed first.

Cell 2 — Register as a SQL Table
Python Cell 2 — Create Temporary SQL View
spark.createDataFrame(data, [“employee”, “sales”, “region”]) \
    .createOrReplaceTempView(“sales_table”)
What Is Happening Here

This cell does two things in one step. spark.createDataFrame(data, […]) converts the Python list into a structured Spark DataFrame — Databricks’ internal format for tabular data — and assigns column names: “employee”, “sales”, and “region”. .createOrReplaceTempView(“sales_table”) then registers this DataFrame as a temporary SQL table called sales_table. Think of this as setting up a whiteboard in the room: you are giving the data a name and a structure so that SQL queries can refer to it by that name in any cell below. The table only exists for the duration of this notebook session — it is not permanently saved anywhere yet. No output appears for this cell, which is normal — it is a setup step, not a display step.

Cell 3 — View the Full Dataset with SQL
SQL Cell 3 — SELECT All Rows
SELECT * FROM sales_table;
Expected Output
employeesalesregion
Alice500west
BobNULLEast
Charlie450north
What Is Happening Here

SELECT * means “show every column.” FROM sales_table tells SQL where to find the data. The result is the full dataset displayed as a formatted table — all three rows, all three columns, with Bob’s NULL value clearly visible. This is the baseline view: you are looking at the raw data through SQL before making any changes. In a real pipeline, analysts run this query first to visually confirm the data loaded correctly and to identify exactly which problems need fixing.

Cell 4 — Filter Out Missing Values
SQL Cell 4 — Remove NULL Sales Rows
SELECT * FROM sales_table
WHERE sales IS NOT NULL;
Expected Output
employeesalesregion
Alice500west
Charlie450north
What Is Happening Here

The WHERE clause acts as a filter — it tests every row against the condition and only returns rows that pass. The condition here is sales IS NOT NULL — meaning “only include this row if the sales column contains a real value.” Bob’s row has NULL in the sales column, so it fails the test and is excluded. Alice and Charlie both have real values, so they pass. The result is a two-row dataset with no missing values. This is one of the most frequently used filters in any data pipeline — incomplete records must be removed before any aggregation or reporting takes place.

Cell 5 — Standardize Text to Uppercase
SQL Cell 5 — UPPER() Text Standardisation
SELECT employee, sales, UPPER(region) AS cleaned_region
FROM sales_table;
Expected Output
employeesalescleaned_region
Alice500WEST
BobNULLEAST
Charlie450NORTH
What Is Happening Here

Instead of SELECT *, this query selects specific columns — employee and sales — and then applies a function to the third column. UPPER(region) converts every value in the region column to uppercase, regardless of how it was originally entered. AS cleaned_region renames the output column to make clear it has been processed. Notice that Bob’s row still appears here — this query only fixes the formatting problem, not the missing value problem. Both issues need to be addressed together, which is what Cell 6 does. This query also demonstrates that you can apply transformations to individual columns without affecting others — a key feature of SQL’s precision.

Cell 6 — The Full Cleaned Dataset
SQL Cell 6 — Filter and Standardize Together
SELECT employee, sales, UPPER(region) AS region
FROM sales_table
WHERE sales IS NOT NULL;
Expected Output
employeesalesregion
Alice500WEST
Charlie450NORTH
What Is Happening Here

This is the complete cleaning query — it combines both operations from Cells 4 and 5 into a single statement. WHERE sales IS NOT NULL removes Bob’s row because his sales value is missing. UPPER(region) standardises the remaining region values to uppercase. The result is a clean, consistent, two-row dataset: no missing values, no formatting inconsistencies. This output is exactly what Unit 7 will save to a permanent Delta table — the finished product of the cleaning stage. In a real pipeline, this single query might apply dozens of conditions and functions simultaneously, but the structure is always the same: SELECT what you want, FROM where it lives, WHERE it meets your quality rules.

Cleaning is the middle of the pipeline — it sits between loading the data and saving the output. Everything that comes before it (S3 storage, Lambda triggers, notebook setup) exists to get data to this point. Everything that comes after it (Delta tables, dashboards, reports) depends on this step having been done correctly.

CSV
Raw file uploaded to S3
Unit 3
Done
↓
READ
Databricks reads and inspects the dataset
Unit 5
Done
↓
CLN
SQL cleans and transforms the dataset
This unit — missing values filtered, text standardised, output ready
Now
↓
OUT
Clean output saved to a Delta table
Unit 7 — the cleaned result becomes a permanent, queryable output
Next
What Uncleaned Data Costs Downstream
Dashboards Show Wrong Figures
A regional sales dashboard groups results by the “region” column. If that column contains “west”, “West”, and “WEST” as three separate values, the dashboard shows three separate bars instead of one. The total for the Western region appears to be a third of what it actually is — a silent, invisible error that distorts every decision made from it.
Averages and Totals Fail
A finance report calculates average monthly sales. If three of the 50 rows have NULL in the sales column and they are not filtered out first, the calculation either fails with an error or silently excludes those rows — producing an average based on 47 records while appearing to summarise all 50.
A Rule Worth Remembering

Clean data does not make a bad analysis good — but dirty data makes a good analysis wrong. The quality of every insight, report, and decision that comes out of a pipeline is bounded by the quality of the data that went in. Cleaning is not optional; it is the contract the pipeline makes with everyone who relies on its output.

Knowledge Check

Five questions covering the key concepts from Unit 6. Select the best answer for each question.

1. What does the SQL keyword WHERE do in a query?

2. Why does Bob’s row disappear when the query WHERE sales IS NOT NULL is applied?

3. What does UPPER(region) AS cleaned_region produce in the output?

4. Why does a regional sales dashboard show three separate entries for West if the region column contains “west”, “West”, and “WEST”?

5. What is the purpose of createOrReplaceTempView("sales_table") in Cell 2?

Unit 6 Summary

What you covered in this unit

Data Cleaning

The process of identifying and fixing problems in a dataset — missing values, inconsistent formatting, duplicates — before the data is used for reporting or decisions.

SQL in Databricks

SQL queries run in dedicated SQL cells. They read from temporary tables created from Python DataFrames and return clean, filtered results without modifying the source.

IS NOT NULL

A WHERE condition that filters out rows where a specified column has no value. Essential for removing incomplete records before any aggregation or reporting.

UPPER()

A SQL function that converts text to uppercase, ensuring consistent formatting regardless of how values were originally entered. Prevents silent grouping errors in reports.

Data Cleaning Transformation NULL SELECT FROM WHERE IS NOT NULL UPPER() AS (alias) TempView DataFrame Spark