Aim: By the end of this page you can read a Databricks notebook and explain the three skills behind it: SQL to ask questions of a table (SELECT, WHERE, JOIN, GROUP BY), Python to read and clean a file (lists, dictionaries, functions, loops, try / except), and a pipeline of four steps, file → clean → table → report.
Description: Databricks is built for people who can ask questions in SQL, move data with Python and think in pipelines. Without these three skills a small bad row, such as order 5005 for a customer who does not exist, becomes a long Monday: nobody can tell which step went wrong. On this page the new engineer Ravi learns the three skills inside a look-alike Databricks workspace, and then you run the very same SQL, Python and a tiny pipeline on your own laptop with duckdb.
Before you start: nothing special. A laptop with Python and pip install duckdb is enough; Databricks Free Edition is a bonus.
On Databricks (Free Edition or any workspace with Unity Catalog) open a notebook and run the setup cells once: SQL cells for the catalog and tables, one Python cell for the landing file. On your laptop install duckdb:
pip install duckdb python setup_regularmart_local.py
💸 Free to practise. Databricks Free Edition runs the notebook cells; the laptop mirror needs only pip install duckdb. To start again on Databricks: DROP CATALOG regularmart CASCADE; on the laptop delete regularmart.duckdb and the landing folder, then run the setup again.
Create the catalog and tables on Databricks (run once · paste into SQL cells, or use 📋 Copy):
-- Databricks notebook · Step 1 · run these cells ONCE (Unity Catalog is on in Databricks Free Edition).
-- Cell 1 (SQL): the catalog, the three schemas and the landing volume
CREATE CATALOG IF NOT EXISTS regularmart;
USE CATALOG regularmart;
CREATE SCHEMA IF NOT EXISTS bronze;
CREATE SCHEMA IF NOT EXISTS silver;
CREATE SCHEMA IF NOT EXISTS gold;
CREATE VOLUME IF NOT EXISTS bronze.landing;
-- Cell 2 (SQL): the customers (order 5005 will belong to customer 6, who is NOT in this table)
CREATE OR REPLACE TABLE silver.customers (customer_id INT, name STRING, city STRING);
INSERT INTO silver.customers VALUES
(1, 'Arjun', 'Hyderabad'), (2, 'Divya', 'Chennai'), (3, 'Farhan', 'Mumbai'),
(4, 'Lakshmi', 'Bengaluru'), (5, 'Rahul', 'Delhi');
# Cell 3 (Python, add %python on the first line of a SQL notebook): the nightly orders file lands in the volume
orders_csv = """order_id,customer_id,product,amount,order_date
5001,1,Mobile,15000,2024-01-05
5002,2,Laptop,55000,2024-01-07
5003,1,Headphones,2000,2024-01-09
5004,4,Watch,3500,2024-01-10
5005,6,Shoes,2500,2024-01-11
"""
open("/Volumes/regularmart/bronze/landing/orders.csv", "w").write(orders_csv)
-- Cell 4 (SQL): bronze = the file as it came, silver = only orders whose customer exists, gold = one row per day
CREATE OR REPLACE TABLE bronze.orders_raw AS
SELECT * FROM read_files('/Volumes/regularmart/bronze/landing/orders.csv', format => 'csv', header => true);
CREATE OR REPLACE TABLE silver.orders AS
SELECT CAST(order_id AS INT) AS order_id, CAST(customer_id AS INT) AS customer_id, product, CAST(amount AS INT) AS amount, CAST(order_date AS DATE) AS order_date
FROM bronze.orders_raw WHERE CAST(customer_id AS INT) IN (SELECT customer_id FROM silver.customers);
CREATE OR REPLACE TABLE gold.daily_sales AS
SELECT order_date, COUNT(*) AS orders, SUM(amount) AS sales FROM silver.orders GROUP BY order_date;The same tables on your laptop (run once · python setup_regularmart_local.py · this file also holds the small GRANT checker that produced every ✅ real output below):
# setup_regularmart_local.py · RegularMart on your laptop: duckdb tables, two landing files and a tiny four-step pipeline
# pip install duckdb then: python setup_regularmart_local.py
# The database file is called regularmart, so duckdb gives you the same three-level names as Databricks: regularmart.silver.orders
import csv, os, duckdb
ORDERS_CSV = """order_id,customer_id,product,amount,order_date
5001,1,Mobile,15000,2024-01-05
5002,2,Laptop,55000,2024-01-07
5003,1,Headphones,2000,2024-01-09
5004,4,Watch,3500,2024-01-10
5005,6,Shoes,2500,2024-01-11
"""
LATE_CSV = """order_id,customer_id,product,amount,order_date
5006,3,Watch,3500,2024-03-10
5007,2,Shoes,,2024-03-11
"""
CUSTOMERS = [(1, "Arjun", "Hyderabad"), (2, "Divya", "Chennai"), (3, "Farhan", "Mumbai"), (4, "Lakshmi", "Bengaluru"), (5, "Rahul", "Delhi")]
# ---- the four stations of the pipeline: read file -> clean -> load table -> report ---------------------------
def read_file(path):
"""station 1: read the landing file; every value is still TEXT"""
with open(path, newline="") as f:
return list(csv.DictReader(f))
def clean(rows, valid_customers):
"""station 2: text -> numbers; rows that cannot be trusted go to `rejected` with a reason (never silently dropped)"""
good, rejected = [], []
for r in rows:
try:
row = (int(r["order_id"]), int(r["customer_id"]), r["product"].strip(), int(r["amount"]), r["order_date"])
except ValueError as e:
rejected.append((r["order_id"], "bad number: " + str(e))); continue
if row[1] not in valid_customers:
rejected.append((r["order_id"], "customer %d does not exist" % row[1])); continue
good.append(row)
return good, rejected
def load(con, good, replace=True):
"""station 3: save the clean rows as the table regularmart.silver.orders (replace=True is safe to repeat)"""
con.execute("CREATE TABLE IF NOT EXISTS regularmart.silver.orders (order_id INT, customer_id INT, product VARCHAR, amount INT, order_date DATE)")
if replace: con.executemany("DELETE FROM regularmart.silver.orders WHERE order_id = ?", [(r[0],) for r in good])
con.executemany("INSERT INTO regularmart.silver.orders VALUES (?, ?, ?, ?, ?)", good)
def report(con):
"""station 4: the question Priya's dashboard asks"""
return con.execute("""SELECT COUNT(*) AS orders, SUM(amount) AS total_sales FROM regularmart.silver.orders""").fetchone()
def run_pipeline(con, path, replace=True):
raw = read_file(path)
good, rejected = clean(raw, {r[0] for r in con.execute("SELECT customer_id FROM regularmart.silver.customers").fetchall()})
load(con, good, replace)
print("%s: %d rows read, %d clean, %d rejected %s" % (os.path.basename(path), len(raw), len(good), len(rejected), rejected))
return report(con)
def fmt(cols, rows):
cells = [[str(c) for c in cols]] + [["" if v is None else str(v) for v in r] for r in rows]
w = [max(len(r[i]) for r in cells) for i in range(len(cols))]
return "\n".join(" ".join(r[i].rjust(w[i]) if r[i].replace(".", "").replace("-", "").isdigit() else r[i].ljust(w[i]) for i in range(len(cols))).rstrip() for r in cells)
def start():
"""open the laptop database (the first night's file has already gone through the pipeline)"""
return duckdb.connect("regularmart.duckdb")
def build():
os.makedirs("landing", exist_ok=True)
open("landing/orders.csv", "w").write(ORDERS_CSV); open("landing/orders_late.csv", "w").write(LATE_CSV)
if os.path.exists("regularmart.duckdb"): os.remove("regularmart.duckdb")
con = duckdb.connect("regularmart.duckdb")
for s in ("bronze", "silver", "gold"): con.execute("CREATE SCHEMA " + s)
con.execute("CREATE TABLE silver.customers (customer_id INT, name VARCHAR, city VARCHAR)")
con.executemany("INSERT INTO silver.customers VALUES (?, ?, ?)", CUSTOMERS)
con.execute("""CREATE TABLE bronze.orders_raw AS SELECT * FROM read_csv('landing/orders.csv', header = true, columns = {'order_id': 'INT', 'customer_id': 'INT', 'product': 'VARCHAR', 'amount': 'INT', 'order_date': 'DATE'})""")
print("first night:", run_pipeline(con, "landing/orders.csv"))
con.execute("""CREATE TABLE gold.daily_sales AS SELECT order_date, COUNT(*) AS orders, SUM(amount) AS sales FROM silver.orders GROUP BY order_date ORDER BY order_date""")
for t in ("bronze.orders_raw", "silver.customers", "silver.orders", "gold.daily_sales"):
print(t.ljust(20), con.execute("SELECT COUNT(*) FROM regularmart." + t).fetchone()[0], "rows")
if __name__ == "__main__": build()The notebook creates the catalog regularmart with schemas bronze, silver and gold and a landing volume, then silver.customers (5 customers), the landing file orders.csv (5 orders: order 5005 belongs to customer 6, who does not exist), bronze.orders_raw (the file as it came), silver.orders (the 4 orders with a real customer, total 75,500) and gold.daily_sales (one row per day). The laptop script does the same with duckdb and Python, writes a second file orders_late.csv for the 2 a.m. scenario, and defines the four pipeline functions read_file, clean, load and report.
These are the two landing files and the tables the setup creates (read back from the laptop mirror). The same rows appear in the animation.
landing/orders.csv · the first night, 5 orders
order_id,customer_id,product,amount,order_date 5001,1,Mobile,15000,2024-01-05 5002,2,Laptop,55000,2024-01-07 5003,1,Headphones,2000,2024-01-09 5004,4,Watch,3500,2024-01-10 5005,6,Shoes,2500,2024-01-11
landing/orders_late.csv · the 2 a.m. file
order_id,customer_id,product,amount,order_date 5006,3,Watch,3500,2024-03-10 5007,2,Shoes,,2024-03-11
bronze.orders_raw (the file as it came · order 5005 → customer 6 does not exist) 5 rows
| order_id | customer_id | product | amount | order_date |
|---|---|---|---|---|
| 5001 | 1 | Mobile | 15000 | 2024-01-05 |
| 5002 | 2 | Laptop | 55000 | 2024-01-07 |
| 5003 | 1 | Headphones | 2000 | 2024-01-09 |
| 5004 | 4 | Watch | 3500 | 2024-01-10 |
| 5005 | 6 | Shoes | 2500 | 2024-01-11 |
silver.customers 5 rows
| customer_id | name | city |
|---|---|---|
| 1 | Arjun | Hyderabad |
| 2 | Divya | Chennai |
| 3 | Farhan | Mumbai |
| 4 | Lakshmi | Bengaluru |
| 5 | Rahul | Delhi |
silver.orders (only orders with a real customer · total 75,500) 4 rows
| order_id | customer_id | product | amount | order_date |
|---|---|---|---|---|
| 5001 | 1 | Mobile | 15000 | 2024-01-05 |
| 5002 | 2 | Laptop | 55000 | 2024-01-07 |
| 5003 | 1 | Headphones | 2000 | 2024-01-09 |
| 5004 | 4 | Watch | 3500 | 2024-01-10 |
gold.daily_sales (one row per day) 4 rows
| order_date | orders | sales |
|---|---|---|
| 2024-01-05 | 1 | 15000 |
| 2024-01-07 | 1 | 55000 |
| 2024-01-09 | 1 | 2000 |
| 2024-01-10 | 1 | 3500 |
Task 1 🧾 It is Friday evening and finance asks Priya for the big orders of the week: every order above 3000 rupees, the biggest first. Write the query on silver.orders.
💭 Hint: SELECT the columns, FROM the table (three-part name on Databricks), WHERE amount > 3000, ORDER BY amount DESC.
SELECT order_id, product, amount FROM regularmart.silver.orders WHERE amount > 3000 ORDER BY amount DESC;
from setup_regularmart_local import *
con = start()
print(fmt(["order_id", "product", "amount"], con.execute("""SELECT order_id, product, amount FROM regularmart.silver.orders
WHERE amount > 3000 ORDER BY amount DESC""").fetchall()))✅ real output · run on this laptop with Python and duckdb (the same SQL and Python ideas as in the Databricks notebook)
order_id product amount
5002 Laptop 55000
5001 Mobile 15000
5004 Watch 3500Task 2 🧮 The manager asks two numbers before the meeting: how many orders are in silver.orders and what is the total sales? Answer with one query.
💭 Hint: COUNT(*) counts rows, SUM(amount) adds a column. Give each a name with AS.
SELECT COUNT(*) AS orders, SUM(amount) AS total_sales FROM regularmart.silver.orders;
from setup_regularmart_local import *
con = start()
print(fmt(["orders", "total_sales"], con.execute("SELECT COUNT(*) AS orders, SUM(amount) AS total_sales FROM regularmart.silver.orders").fetchall()))✅ real output · run on this laptop with Python and duckdb (the same SQL and Python ideas as in the Databricks notebook)
orders total_sales
4 75500Task 3 🔗 Priya wants the customer name next to every raw order. Join bronze.orders_raw to silver.customers on customer_id and count the rows: how many of the 5 raw orders survive?
💭 Hint: JOIN … ON o.customer_id = c.customer_id. An INNER JOIN keeps only orders whose customer exists.
SELECT o.order_id, c.name, o.product, o.amount FROM regularmart.bronze.orders_raw o JOIN regularmart.silver.customers c ON o.customer_id = c.customer_id ORDER BY o.order_id;
from setup_regularmart_local import *
con = start()
rows = con.execute("""SELECT o.order_id, c.name, o.product, o.amount FROM regularmart.bronze.orders_raw o
JOIN regularmart.silver.customers c ON o.customer_id = c.customer_id ORDER BY o.order_id""").fetchall()
print(fmt(["order_id", "name", "product", "amount"], rows))
print("raw orders: 5 · rows after the INNER JOIN:", len(rows))✅ real output · run on this laptop with Python and duckdb (the same SQL and Python ideas as in the Databricks notebook)
order_id name product amount
5001 Arjun Mobile 15000
5002 Divya Laptop 55000
5003 Arjun Headphones 2000
5004 Lakshmi Watch 3500
raw orders: 5 · rows after the INNER JOIN: 4Task 4 🕵️ The dashboard is short by 2500 rupees. Use a LEFT JOIN to list every raw order and find the one that has no customer.
💭 Hint: LEFT JOIN keeps every order; a missing customer shows as null. Then add WHERE c.name IS NULL.
SELECT o.order_id, c.name, o.product, o.amount FROM regularmart.bronze.orders_raw o LEFT JOIN regularmart.silver.customers c ON o.customer_id = c.customer_id WHERE c.name IS NULL;
from setup_regularmart_local import *
con = start()
print(fmt(["order_id", "name", "product", "amount"], con.execute("""SELECT o.order_id, c.name, o.product, o.amount FROM regularmart.bronze.orders_raw o
LEFT JOIN regularmart.silver.customers c ON o.customer_id = c.customer_id WHERE c.name IS NULL""").fetchall()))✅ real output · run on this laptop with Python and duckdb (the same SQL and Python ideas as in the Databricks notebook)
order_id name product amount
5005 Shoes 2500Task 5 📊 Monday morning: how much did RegularMart sell in each city? Join silver.orders to silver.customers, group by city, count the orders and sum the sales, biggest city first.
💭 Hint: GROUP BY c.city, COUNT(*) AS orders, SUM(o.amount) AS sales, ORDER BY sales DESC. Every SELECT column is an aggregate or is in GROUP BY.
SELECT c.city, COUNT(*) AS orders, SUM(o.amount) AS sales FROM regularmart.silver.orders o JOIN regularmart.silver.customers c ON o.customer_id = c.customer_id GROUP BY c.city ORDER BY sales DESC;
from setup_regularmart_local import *
con = start()
print(fmt(["city", "orders", "sales"], con.execute("""SELECT c.city, COUNT(*) AS orders, SUM(o.amount) AS sales FROM regularmart.silver.orders o
JOIN regularmart.silver.customers c ON o.customer_id = c.customer_id GROUP BY c.city ORDER BY sales DESC""").fetchall()))✅ real output · run on this laptop with Python and duckdb (the same SQL and Python ideas as in the Databricks notebook)
city orders sales Chennai 1 55000 Hyderabad 2 17000 Bengaluru 1 3500
Task 6 🔤 A file line is only text: "5001,1,Mobile,15000,2024-01-05". Split it into pieces, show that adding two amounts as text glues them together, then build a dictionary with a real number for the amount.
💭 Hint: line.split(",") gives a list; int(piece) gives a number; {"key": value} is a dictionary.
# Python cell in a notebook
line = "5001,1,Mobile,15000,2024-01-05"
parts = line.split(",")
print(parts)
print("15000" + "2000") # text is glued, not added
order = {"order_id": int(parts[0]), "product": parts[2], "amount": int(parts[3])}
print(order["amount"] + 2000, order)line = "5001,1,Mobile,15000,2024-01-05"
parts = line.split(",")
print(parts)
print("15000" + "2000")
order = {"order_id": int(parts[0]), "product": parts[2], "amount": int(parts[3])}
print(order["amount"] + 2000, order)✅ real output · run on this laptop with Python and duckdb (the same SQL and Python ideas as in the Databricks notebook)
['5001', '1', 'Mobile', '15000', '2024-01-05']
150002000
17000 {'order_id': 5001, 'product': 'Mobile', 'amount': 15000}Task 7 🔁 Write a function to_order(line) and loop over the 5 lines of orders.csv to add up the amounts. Compare the Python total with Priya’s report (75,500) and name the line that explains the difference.
💭 Hint: Open the file, skip the header, call to_order on each line. The difference is the order whose customer does not exist.
def to_order(line):
p = line.strip().split(",")
return {"id": int(p[0]), "cust": int(p[1]), "amount": int(p[3])}
lines = open("/Volumes/regularmart/bronze/landing/orders.csv").read().splitlines()[1:]
total = 0
for line in lines:
total += to_order(line)["amount"]
print(total)def to_order(line):
p = line.strip().split(",")
return {"id": int(p[0]), "cust": int(p[1]), "amount": int(p[3])}
lines = open("landing/orders.csv").read().splitlines()[1:]
total = 0
for line in lines:
total += to_order(line)["amount"]
print("Python total:", total, "· Priya's report: 75500 · difference:", total - 75500)
print("the lines whose customer is not in 1..5:", [to_order(l)["id"] for l in lines if to_order(l)["cust"] > 5])✅ real output · run on this laptop with Python and duckdb (the same SQL and Python ideas as in the Databricks notebook)
Python total: 78000 · Priya's report: 75500 · difference: 2500 the lines whose customer is not in 1..5: [5005]
Task 8 🛑 At two in the morning orders_late.csv arrives, and order 5007 has an empty amount. A plain int() crashes the job. Rewrite the loop so bad rows go to a rejected list and the good rows are kept.
💭 Hint: Put int(...) inside try, catch ValueError in except, and append the order id to a list called bad.
rows = open("/Volumes/regularmart/bronze/landing/orders_late.csv").read().splitlines()[1:]
good, bad = [], []
for line in rows:
try: good.append(int(line.split(",")[3]))
except ValueError: bad.append(line.split(",")[0])
print(len(good), "good,", len(bad), "rejected:", bad)rows = open("landing/orders_late.csv").read().splitlines()[1:]
try:
[int(line.split(",")[3]) for line in rows]
except ValueError as e:
print("without try/except the job stops:", e)
good, bad = [], []
for line in rows:
try: good.append(int(line.split(",")[3]))
except ValueError: bad.append(line.split(",")[0])
print(len(good), "good,", len(bad), "rejected:", bad)✅ real output · run on this laptop with Python and duckdb (the same SQL and Python ideas as in the Databricks notebook)
without try/except the job stops: invalid literal for int() with base 10: '' 1 good, 1 rejected: ['5007']
Task 9 🏭 Run the first night's file through the whole pipeline: read the file, clean it, load silver.orders, and report. Print how many rows went in, how many came out and which row was rejected.
💭 Hint: Four functions: read_file, clean, load, report (they are in setup_regularmart_local.py). Print the counts at every step.
# the same four stations on Databricks (PySpark + SQL)
df = spark.read.csv("/Volumes/regularmart/bronze/landing/orders.csv", header=True, inferSchema=True) # 1 read file
good = df.join(spark.table("regularmart.silver.customers"), "customer_id", "left_semi") # 2 clean: customer must exist
good.write.mode("overwrite").saveAsTable("regularmart.silver.orders") # 3 load table
spark.sql("SELECT COUNT(*) AS orders, SUM(amount) AS total_sales FROM regularmart.silver.orders").show() # 4 reportfrom setup_regularmart_local import *
con = start()
con.execute("DELETE FROM regularmart.silver.orders") # start from an empty table
print("orders, total_sales =", run_pipeline(con, "landing/orders.csv"))✅ real output · run on this laptop with Python and duckdb (the same SQL and Python ideas as in the Databricks notebook)
orders.csv: 5 rows read, 4 clean, 1 rejected [('5005', 'customer 6 does not exist')]
orders, total_sales = (4, 75500)Task 10 ♻️ The nightly job failed halfway and Suresh pressed Run again. Show what a load that only INSERTs does when the file is loaded twice, then show a load that replaces rows by order_id.
💭 Hint: replace=False simply appends. replace=True first deletes the rows with the same order_id, so the second run changes nothing.
-- risky: adds the same rows on every run INSERT INTO regularmart.silver.orders SELECT * FROM clean_rows; -- safe to repeat: the table is rebuilt from the clean rows each time CREATE OR REPLACE TABLE regularmart.silver.orders AS SELECT * FROM clean_rows;
from setup_regularmart_local import *
con = start()
con.execute("DELETE FROM regularmart.silver.orders")
run_pipeline(con, "landing/orders.csv", replace=False); print("INSERT, run 1:", report(con))
run_pipeline(con, "landing/orders.csv", replace=False); print("INSERT, run 2:", report(con), "<- doubled")
con.execute("DELETE FROM regularmart.silver.orders")
run_pipeline(con, "landing/orders.csv", replace=True); print("REPLACE, run 1:", report(con))
run_pipeline(con, "landing/orders.csv", replace=True); print("REPLACE, run 2:", report(con), "<- same")✅ real output · run on this laptop with Python and duckdb (the same SQL and Python ideas as in the Databricks notebook)
orders.csv: 5 rows read, 4 clean, 1 rejected [('5005', 'customer 6 does not exist')]
INSERT, run 1: (4, 75500)
orders.csv: 5 rows read, 4 clean, 1 rejected [('5005', 'customer 6 does not exist')]
INSERT, run 2: (8, 151000) <- doubled
orders.csv: 5 rows read, 4 clean, 1 rejected [('5005', 'customer 6 does not exist')]
REPLACE, run 1: (4, 75500)
orders.csv: 5 rows read, 4 clean, 1 rejected [('5005', 'customer 6 does not exist')]
REPLACE, run 2: (4, 75500) <- sameSELECT COUNT(*) AS orders, SUM(amount) AS total_sales FROM regularmart.silver.orders; -- SQL asks
from setup_regularmart_local import *
con = start()
print("SQL asks :", con.execute("SELECT COUNT(*), SUM(amount) FROM regularmart.silver.orders").fetchone())
good, rejected = clean(read_file("landing/orders.csv"), {1, 2, 3, 4, 5})
print("Python moves and cleans:", len(good), "good rows,", rejected)✅ real output · run on this laptop with Python and duckdb (the same SQL and Python ideas as in the Databricks notebook)
SQL asks : (4, 75500)
Python moves and cleans: 4 good rows, [('5005', 'customer 6 does not exist')]💡 Say this in the interview: “SQL asks questions of tables, Python moves and cleans data, and in a Databricks notebook they work together on the same tables.”
SELECT o.order_id FROM regularmart.bronze.orders_raw o LEFT JOIN regularmart.silver.customers c ON o.customer_id = c.customer_id WHERE c.customer_id IS NULL;
from setup_regularmart_local import *
con = start()
print("inner:", con.execute("SELECT COUNT(*) FROM regularmart.bronze.orders_raw o JOIN regularmart.silver.customers c ON o.customer_id = c.customer_id").fetchone()[0], "rows")
print("left :", con.execute("SELECT COUNT(*) FROM regularmart.bronze.orders_raw o LEFT JOIN regularmart.silver.customers c ON o.customer_id = c.customer_id").fetchone()[0], "rows")
print("orphans:", con.execute("SELECT o.order_id FROM regularmart.bronze.orders_raw o LEFT JOIN regularmart.silver.customers c ON o.customer_id = c.customer_id WHERE c.customer_id IS NULL").fetchall())✅ real output · run on this laptop with Python and duckdb (the same SQL and Python ideas as in the Databricks notebook)
inner: 4 rows left : 5 rows orphans: [(5005,)]
💡 Say this in the interview: “An inner join keeps only matches, a left join keeps everything from the left table, so a left join with IS NULL finds the orders that have no customer.”
-- Lakeflow Jobs: tasks read_file → clean → load_table → report, schedule daily at 02:00, alert on failure
from setup_regularmart_local import *
con = start()
con.execute("DELETE FROM regularmart.silver.orders")
print("orders, total_sales =", run_pipeline(con, "landing/orders.csv"))✅ real output · run on this laptop with Python and duckdb (the same SQL and Python ideas as in the Databricks notebook)
orders.csv: 5 rows read, 4 clean, 1 rejected [('5005', 'customer 6 does not exist')]
orders, total_sales = (4, 75500)💡 Say this in the interview: “A pipeline is a few steps in order, file, clean, table and report, and at every step I check the row counts so I know where a number changed.”
# rejected rows are written to their own table with the reason
rejected_df.write.mode("append").saveAsTable("regularmart.bronze.orders_rejected")from setup_regularmart_local import *
for f in ("orders.csv", "orders_late.csv"):
good, rejected = clean(read_file("landing/" + f), {1, 2, 3, 4, 5})
print(f, "->", len(good), "good,", len(rejected), "rejected:", rejected)✅ real output · run on this laptop with Python and duckdb (the same SQL and Python ideas as in the Databricks notebook)
orders.csv -> 4 good, 1 rejected: [('5005', 'customer 6 does not exist')]
orders_late.csv -> 1 good, 1 rejected: [('5007', "bad number: invalid literal for int() with base 10: ''")]💡 Say this in the interview: “I validate every row, keep the good ones, set the bad ones aside with the reason, and report the count, so one bad row never stops the pipeline or hides in the totals.”
CREATE OR REPLACE TABLE regularmart.silver.orders AS SELECT * FROM clean_rows; -- safe to repeat
from setup_regularmart_local import *
con = start()
con.execute("DELETE FROM regularmart.silver.orders")
for i in (1, 2, 3): run_pipeline(con, "landing/orders.csv", replace=True)
print("after 3 runs:", report(con))✅ real output · run on this laptop with Python and duckdb (the same SQL and Python ideas as in the Databricks notebook)
orders.csv: 5 rows read, 4 clean, 1 rejected [('5005', 'customer 6 does not exist')]
orders.csv: 5 rows read, 4 clean, 1 rejected [('5005', 'customer 6 does not exist')]
orders.csv: 5 rows read, 4 clean, 1 rejected [('5005', 'customer 6 does not exist')]
after 3 runs: (4, 75500)💡 Say this in the interview: “Idempotent means running the step again gives the same result, so I load by replacing or merging on the key instead of blindly inserting.”
Go-live night. Start from an empty silver.orders. Run orders.csv, then the late file orders_late.csv (order 5006 for Farhan and a row with an empty amount), then run the late file a second time. Print four PASS / FAIL checks: 5 orders in silver, total sales 79,000, the second run changed nothing, and the rejected rows are 5005 and 5007.
💭 Hint: Use run_pipeline(con, file) three times with replace=True; collect the rejected ids from clean(read_file(...)).
-- Lakeflow Jobs: schedule at 02:00, task order read_file → clean → load_table → report, retry on failure. -- load_table uses CREATE OR REPLACE / MERGE, so a retry or a repair run never doubles the data.
from setup_regularmart_local import *
con = start()
con.execute("DELETE FROM regularmart.silver.orders")
run_pipeline(con, "landing/orders.csv")
after_late = run_pipeline(con, "landing/orders_late.csv")
again = run_pipeline(con, "landing/orders_late.csv")
rej = [r[0] for f in ("orders.csv", "orders_late.csv") for r in clean(read_file("landing/" + f), {1, 2, 3, 4, 5})[1]]
def check(label, ok): print("PASS" if ok else "FAIL", "·", label)
check("5 orders in silver", after_late[0] == 5)
check("total sales 79000", after_late[1] == 79000)
check("second run changed nothing", again == after_late)
check("rejected are 5005 and 5007", rej == ["5005", "5007"])✅ real output · run on this laptop with Python and duckdb (the same SQL and Python ideas as in the Databricks notebook)
orders.csv: 5 rows read, 4 clean, 1 rejected [('5005', 'customer 6 does not exist')]
orders_late.csv: 2 rows read, 1 clean, 1 rejected [('5007', "bad number: invalid literal for int() with base 10: ''")]
orders_late.csv: 2 rows read, 1 clean, 1 rejected [('5007', "bad number: invalid literal for int() with base 10: ''")]
PASS · 5 orders in silver
PASS · total sales 79000
PASS · second run changed nothing
PASS · rejected are 5005 and 5007