Databricks · 01

Prerequisites: SQL, Python and pipelines

📚 RegularMart · SQL · Python · pipelines
🗂️

🗒️ Step-by-step notes

🎯 Student AIM read this first · what you will learn on this page

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.

🤔 Why learn these three first?

  • Every Databricks page after this one uses SQL cells, Python cells and jobs.
  • Reading an error message is much easier when you know what the code is doing.
  • Analysts speak SQL, engineers speak Python, managers speak pipeline: you can talk to all three.
  • “Join, group by, a Python function, what is a pipeline?” are the first questions of a data engineering interview.

🌍 Where is it used?

  • 🛒 Online shops: a nightly orders file is cleaned with Python and reported with SQL.
  • 🛵 Delivery apps: yesterday’s numbers by city with one GROUP BY.
  • 🏦 Banks: a failed load must name the bad row and the reason.
  • 🏥 Hospitals: a late file must never count a patient twice.
  • 🧑‍💻 New engineers: read yesterday’s notebook to learn how the numbers are made.

📘 What you will learn

  • Why these skills? One bad row, one long Monday, and the road map.
  • Without / With: guessing and clicking, or reading and checking.
  • SQL: SELECT, WHERE, ORDER BY, INNER and LEFT JOIN, GROUP BY with COUNT and SUM.
  • Python: text to list to dictionary, functions, loops, try / except for bad rows.
  • Pipeline: file, clean, table, report; failures, repair runs, safe re-runs and schedules.
  • Pros / Cons: five strengths, five costs and their fixes.
  • Not a fit: when you should start somewhere else.
  • Compare: Excel vs SQL vs pandas vs PySpark.
  • Clouds: Databricks on AWS, Azure and Google Cloud, and the native tools.
  • Architecture: a tiny pipeline, SQL and Python on one table, scheduled and watched.

✅ After this page you can

  • Write a query with a filter, a join and a group, and read its result.
  • Find the order that has no customer with a LEFT JOIN.
  • Clean a file with a Python function and set bad rows aside with try / except.
  • Draw a four-step pipeline, count rows at every arrow and say why a load must be safe to repeat.
  • Answer the top 5 interview questions below.

Before you start: nothing special. A laptop with Python and pip install duckdb is enough; Databricks Free Edition is a bonus.

🧠 All memory tricks

🧪 Practice Lab real-time scenarios · SQL and Python in a Databricks notebook · and the same on your laptop with duckdb

Step 1 · Setup

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:

Terminal
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 · SQL · setup
-- 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):

Laptop · Python + duckdb · setup_regularmart_local.py
# 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.

Step 2 · Sample data

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

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

landing/orders_late.csv · the 2 a.m. file

CSV
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_idcustomer_idproductamountorder_date
50011Mobile150002024-01-05
50022Laptop550002024-01-07
50031Headphones20002024-01-09
50044Watch35002024-01-10
50056Shoes25002024-01-11

silver.customers 5 rows

customer_idnamecity
1ArjunHyderabad
2DivyaChennai
3FarhanMumbai
4LakshmiBengaluru
5RahulDelhi

silver.orders (only orders with a real customer · total 75,500) 4 rows

order_idcustomer_idproductamountorder_date
50011Mobile150002024-01-05
50022Laptop550002024-01-07
50031Headphones20002024-01-09
50044Watch35002024-01-10

gold.daily_sales (one row per day) 4 rows

order_dateorderssales
2024-01-05115000
2024-01-07155000
2024-01-0912000
2024-01-1013500

Step 3 · Real-time scenario tasks easy → hard · try first, then click

EasySELECT, WHERE, ORDER BY

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.

EasyCOUNT and SUM

Task 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.

MediumINNER JOIN

Task 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.

MediumLEFT JOIN finds the bad row

Task 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.

MediumGROUP BY

Task 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.

EasyText, list, dictionary

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.

MediumFunction and loop

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.

Mediumtry / except

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.

HardA four-station pipeline

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.

HardSafe to repeat

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.

Step 4 · Top 5 interview questions easy → tricky · click to reveal

Step 5 · Mini challenge: 🌙 The 2 a.m. late file: run it twice, nothing doubles

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(...)).