Business Data Investigations — Runnable Original Laboratories

Run these original synthetic laboratories with Python 3. They use only the standard library. The SQL database is created in memory; no real account or production database is used. Save the source into a disposable folder and run the command shown. If a browser blocks the download link, open the complete source and save it as the displayed filename.

SQL: facts, joins, constraints and transactions

Run python sql_lab.py. First predict the expected job rows and totals. Inspect the schema and the deliberately wrong query. Then run the file, explain why each wrong query fails, and attempt the extensions in SQL Units 1–6. The checks report fixture correctness, not a learner grade.

Download sql_lab.py

Open complete runnable source
"""Cedar Service SQL laboratory. Python 3, standard library only.

Run in a disposable folder: python sql_lab.py
The database lives in memory; no real account or production database is used.
Before reading each answer query, predict its row count and totals.
"""
import sqlite3

SCHEMA = """
PRAGMA foreign_keys = ON;
CREATE TABLE customers (
 customer_id INTEGER PRIMARY KEY,
 external_code TEXT NOT NULL UNIQUE,
 name TEXT NOT NULL
);
CREATE TABLE jobs (
 job_id INTEGER PRIMARY KEY,
 customer_id INTEGER NOT NULL REFERENCES customers(customer_id),
 status TEXT NOT NULL CHECK(status IN ('open','completed','cancelled')),
 opened_date TEXT NOT NULL,
 completion_date TEXT
);
CREATE TABLE job_lines (
 line_id INTEGER PRIMARY KEY,
 job_id INTEGER NOT NULL REFERENCES jobs(job_id),
 quantity INTEGER NOT NULL CHECK(quantity > 0),
 unit_cents INTEGER NOT NULL CHECK(unit_cents >= 0)
);
CREATE TABLE payments (
 payment_id INTEGER PRIMARY KEY,
 external_event TEXT NOT NULL UNIQUE,
 job_id INTEGER NOT NULL REFERENCES jobs(job_id),
 amount_cents INTEGER NOT NULL CHECK(amount_cents > 0)
);
INSERT INTO customers VALUES (1,'C001','Cedar'),(2,'C002','Bay'),(3,'C003','Oak');
INSERT INTO jobs VALUES
 (101,1,'completed','2026-01-01','2026-01-03'),
 (102,1,'open','2026-01-20',NULL),
 (103,2,'completed','2026-02-01','2026-02-02');
INSERT INTO job_lines VALUES
 (1,101,1,10000),(2,101,1,15000),(3,102,1,8000),
 (4,103,1,20000),(5,103,1,20000);
INSERT INTO payments VALUES
 (1,'E001',101,6000),(2,'E002',101,4000),
 (3,'E003',102,4000),(4,'E004',103,25000);
"""

RECEIVABLES = """
WITH billed AS (
 SELECT job_id, SUM(quantity * unit_cents) AS billed_cents
 FROM job_lines GROUP BY job_id
), paid AS (
 SELECT job_id, SUM(amount_cents) AS paid_cents
 FROM payments GROUP BY job_id
)
SELECT j.job_id, c.name,
 COALESCE(b.billed_cents,0) AS billed_cents,
 COALESCE(p.paid_cents,0) AS paid_cents,
 COALESCE(b.billed_cents,0)-COALESCE(p.paid_cents,0) AS open_cents
FROM jobs AS j
JOIN customers AS c ON c.customer_id=j.customer_id
LEFT JOIN billed AS b ON b.job_id=j.job_id
LEFT JOIN paid AS p ON p.job_id=j.job_id
ORDER BY j.job_id
"""

def fresh():
    con = sqlite3.connect(':memory:')
    con.executescript(SCHEMA)
    assert con.execute('PRAGMA foreign_keys').fetchone() == (1,)
    return con

def rejected(con, sql, args=()):
    """Prove a particular invalid write fails; preserve the fixture."""
    con.execute('SAVEPOINT invalid_example')
    failed = False
    try:
        con.execute(sql, args)
    except sqlite3.IntegrityError:
        failed = True
    finally:
        con.execute('ROLLBACK TO invalid_example')
        con.execute('RELEASE invalid_example')
    assert failed, 'The invalid state was not rejected.'

def run():
    con = fresh()
    expected = [
        (101,'Cedar',25000,10000,15000),
        (102,'Cedar',8000,4000,4000),
        (103,'Bay',40000,25000,15000),
    ]
    rows = con.execute(RECEIVABLES).fetchall()
    assert rows == expected
    assert len({r[0] for r in rows}) == 3
    assert tuple(sum(r[i] for r in rows) for i in (2,3,4)) == (73000,39000,34000)
    # Independent base-event reconciliation, without the report joins.
    assert con.execute('SELECT SUM(quantity*unit_cents) FROM job_lines').fetchone() == (73000,)
    assert con.execute('SELECT SUM(amount_cents) FROM payments').fetchone() == (39000,)

    # A plausible but WRONG query: two independent child relationships multiply.
    wrong = con.execute('''
      SELECT j.job_id,SUM(l.quantity*l.unit_cents),SUM(p.amount_cents)
      FROM jobs j JOIN job_lines l ON l.job_id=j.job_id
      JOIN payments p ON p.job_id=j.job_id
      WHERE j.job_id=101 GROUP BY j.job_id
    ''').fetchone()
    assert wrong == (101,50000,20000)
    distinct_wrong = con.execute('''
      SELECT SUM(DISTINCT quantity*unit_cents)
      FROM job_lines WHERE job_id=103
    ''').fetchone()
    assert distinct_wrong == (20000,)  # Real total is 40000.

    # Missing values, population definitions, and outer-join filter placement.
    assert con.execute('SELECT COUNT(*),COUNT(completion_date) FROM jobs').fetchone() == (3,2)
    assert con.execute('SELECT AVG(amount_cents) FROM payments').fetchone() == (9750.0,)
    every_customer = con.execute('''
      SELECT c.customer_id,COUNT(j.job_id)
      FROM customers c LEFT JOIN jobs j
      ON j.customer_id=c.customer_id AND j.status='completed'
      GROUP BY c.customer_id ORDER BY c.customer_id
    ''').fetchall()
    assert every_customer == [(1,1),(2,1),(3,0)]
    only_matching = con.execute('''
      SELECT c.customer_id,COUNT(j.job_id)
      FROM customers c LEFT JOIN jobs j ON j.customer_id=c.customer_id
      WHERE j.status='completed'
      GROUP BY c.customer_id ORDER BY c.customer_id
    ''').fetchall()
    assert only_matching == [(1,1),(2,1)]
    assert con.execute('''SELECT customer_id FROM customers c
      WHERE NOT EXISTS (SELECT 1 FROM jobs j WHERE j.customer_id=c.customer_id)
      ORDER BY customer_id''').fetchall() == [(3,)]
    assert con.execute("SELECT job_id FROM jobs WHERE opened_date >= '2026-01-01' AND opened_date < '2026-02-01' ORDER BY job_id").fetchall() == [(101,),(102,)]

    # Constraints reject orphan records, duplicate identities, and bad domains.
    rejected(con,"INSERT INTO jobs VALUES (104,999,'open','2026-02-02',NULL)")
    rejected(con,"INSERT INTO jobs VALUES (101,1,'open','2026-02-02',NULL)")
    rejected(con,"INSERT INTO jobs VALUES (104,1,'nonsense','2026-02-02',NULL)")
    rejected(con,"INSERT INTO job_lines VALUES (6,101,1,-1)")
    rejected(con,"INSERT INTO payments VALUES (5,'E001',101,100)")
    rejected(con,"INSERT INTO customers VALUES (4,NULL,'Missing code')")

    # Transfer A: an entirely unpaid job must not vanish from a LEFT JOIN report.
    con.execute("INSERT INTO jobs VALUES (104,3,'open','2026-02-03',NULL)")
    con.execute('INSERT INTO job_lines VALUES (6,104,1,5000)')
    rows = con.execute(RECEIVABLES).fetchall()
    assert rows[-1] == (104,'Oak',5000,0,5000)
    assert tuple(sum(r[i] for r in rows) for i in (2,3,4)) == (78000,39000,39000)
    con.close()

    # Transfer B starts from the ORIGINAL fixture, not from Transfer A.
    con = fresh()
    con.execute("INSERT INTO payments VALUES (5,'E005',102,4000)")
    rows = con.execute(RECEIVABLES).fetchall()
    assert len(rows) == 3 and rows[1][-1] == 0
    assert tuple(sum(r[i] for r in rows) for i in (2,3,4)) == (73000,43000,30000)
    con.close()

    # Atomicity: deliberately fail between the two halves of a transfer.
    con = sqlite3.connect(':memory:')
    con.execute('CREATE TABLE control_totals(name TEXT PRIMARY KEY,amount INTEGER NOT NULL CHECK(amount>=0))')
    con.executemany('INSERT INTO control_totals VALUES (?,?)',[('available',100),('reserve',100)])
    con.commit()
    try:
        with con:
            con.execute("UPDATE control_totals SET amount=amount-30 WHERE name='available'")
            raise RuntimeError('Deliberate lab failure before the second update')
    except RuntimeError:
        pass
    assert dict(con.execute('SELECT name,amount FROM control_totals')) == {'available':100,'reserve':100}
    with con:
        con.execute("UPDATE control_totals SET amount=amount-30 WHERE name='available'")
        con.execute("UPDATE control_totals SET amount=amount+30 WHERE name='reserve'")
    assert dict(con.execute('SELECT name,amount FROM control_totals')) == {'available':70,'reserve':130}
    assert con.execute('SELECT SUM(amount) FROM control_totals').fetchone() == (200,)
    con.close()
    print('PASS: reconciliations, fanout counterexamples, NULLs, dates, integrity, transfer cases, rollback, commit.')
    print('Independent extensions: add refunds with explicit semantics; add multi-job payment allocations; add currency and prevent mixed-currency totals.')

if __name__ == '__main__':
    run()

Regression, quality and finance: reproduce the reasoning

Run python quantitative_labs.py. Match each calculation to its course unit before changing an input. Separate a change in arithmetic from a change that invalidates the model assumptions. The printed results verify the supplied examples; they do not prove a real-world model is valid.

Download quantitative_labs.py

Open complete runnable source
"""Original Academy quantitative laboratory, Python 3 standard library.

Synthetic educational records. Run: python quantitative_labs.py
Change inputs only after predicting what should change and why.
"""
from math import sqrt, exp, isclose
from statistics import mean

def close(a,b):
    assert isclose(a,b,rel_tol=1e-9,abs_tol=1e-9),(a,b)

def simple_fit(x,y):
    if len(x)!=len(y) or len(x)<3:
        raise ValueError('Need matching observations and n > 2.')
    xb,yb = mean(x),mean(y)
    sxx=sum((v-xb)**2 for v in x)
    if sxx==0:
        raise ValueError('Slope is unidentified when X has no variation.')
    b=sum((a-xb)*(v-yb) for a,v in zip(x,y))/sxx
    a=yb-b*xb
    fitted=[a+b*v for v in x]
    residuals=[v-f for v,f in zip(y,fitted)]
    sse=sum(e*e for e in residuals)
    sst=sum((v-yb)**2 for v in y)
    return dict(intercept=a,slope=b,fitted=fitted,residuals=residuals,
                sse=sse,r2=None if sst==0 else 1-sse/sst,
                s=sqrt(sse/(len(x)-2)),sxx=sxx,xbar=xb)

def metrics(actual,predicted):
    if len(actual)!=len(predicted) or not actual:
        raise ValueError('Need matching nonempty series.')
    errors=[a-p for a,p in zip(actual,predicted)]
    return mean(abs(e) for e in errors),sqrt(mean(e*e for e in errors))

def npv(rate,flows):
    if rate<=-1:
        raise ValueError('This teaching function needs rate > -1.')
    return sum(cash/(1+rate)**t for t,cash in enumerate(flows))

def mm1(arrival,service):
    if not 0<arrival<service:
        raise ValueError('A stable positive-arrival M/M/1 example needs 0 < lambda < mu.')
    return 1/(service-arrival),arrival/(service*(service-arrival))

def run():
    x=[1,2,3,4]; y=[2,4,5,7]
    fit=simple_fit(x,y)
    close(fit['intercept'],.5);close(fit['slope'],1.6)
    close(fit['sse'],.2);close(fit['r2'],1-.2/13)
    close(sum(fit['residuals']),0)
    close(sum(a*e for a,e in zip(x,fit['residuals'])),0)
    shifted=simple_fit(x,[v+10 for v in y])
    close(shifted['intercept'],10.5);close(shifted['slope'],1.6)
    scaled=simple_fit(x,[100*v for v in y])
    close(scaled['slope'],160);close(scaled['s'],100*fit['s'])
    close(scaled['r2'],fit['r2'])
    slope_se=fit['s']/sqrt(fit['sxx'])
    assert .99<1.6-4.303*slope_se<1.00
    assert 2.20<1.6+4.303*slope_se<2.21
    mean_se=fit['s']*sqrt(1/4)
    individual_se=fit['s']*sqrt(1+1/4)
    assert individual_se>mean_se
    pooled=simple_fit(x,[12,14,36,38])
    close(pooled['slope'],10)
    for xx,season,actual in zip(x,[0,0,1,1],[12,14,36,38]):
        close(10+2*xx+20*season,actual)
    for area in (0,5,10,15):
        for emergency in (0,1):
            original=2+.5*area+3*emergency+.2*area*emergency
            centered=7+.5*(area-10)+5*emergency+.2*(area-10)*emergency
            close(original,centered)
    close(100*(exp(.2)-1),22.140275816016985)
    close(metrics([4,6,8,10],[5,5,9,9])[1],1)
    close(metrics([4,6,8,10],[4,6,8,14])[1],2)
    demand=[100,110,105,120,130,125]
    actual=[]; naive=[]; moving=[]
    for origin in range(3,len(demand)):
        history=demand[:origin]  # Future values cannot enter this fit.
        actual.append(demand[origin])
        naive.append(history[-1]);moving.append(mean(history[-3:]))
    close(metrics(actual,naive)[0],10)
    close(metrics(actual,naive)[1],sqrt(350/3))
    close(metrics(actual,moving)[0],40/3)
    close(metrics(actual,moving)[1],sqrt(5450/27))
    level=100
    for observation in [110,105,120,130]:
        level=.5*observation+.5*level
    close(level,121.25)

    # Quality: rates, congestion, monitoring scales, intervention economics.
    close(100/(400+100),120/(420+180))
    close((120/500)/.2-1,.2)
    close(8*.9,7.2);close(8*2.5,20)
    close(mm1(3,6)[0]*60,20)
    close(mm1(5,6)[1]*60,50)
    close(mm1(5.5,6)[0]*60,120)
    close(2/sqrt(4),1);close(2/sqrt(16),.5)
    close((8-12)-(7-10),-1)
    close((8-12)-(4-10),2)
    net5=40*80-1000*5/60*40-1000
    net2=40*80-1000*2/60*40-1000
    close(net5,-1133.3333333333335);close(net2,866.6666666666665)

    # Finance: timelines specified independently of any course text totals.
    base=npv(.10,[-110000,40000,40000,70000])
    downside=npv(.10,[-110000,25000,25000,45000])
    opportunity=npv(.10,[0,6000,6000,6000])
    close(base,12013.523666416193)
    close(downside,-32802.4042073629)
    close(.6*base+.4*downside,-5912.8474830954465)
    close(base-opportunity,-2907.5882794891386)
    close(sqrt(.25*.04+.25*.04),sqrt(.02))
    close(.04+1.2*.05,.10)
    close(.6*.10+.4*.06*(1-.25),.078)
    close(.6*.10+.4*.06,.084)
    for spot,payoff,profit in [(120,20,12),(105,5,-3),(90,0,-8),(108,8,0)]:
        close(max(spot-100,0),payoff);close(payoff-8,profit)
    cash=20000+60000+10000-65000-15000
    close(cash,10000);close(15000-cash,5000)
    close(15000-(cash-20000),25000)
    print('PASS: regression, residual invariants, transformations, confounding fixture, chronological forecasts, quality, and finance.')
    print('Base NPV:',round(base,2),'Downside:',round(downside,2))
    print('Forecast naive MAE/RMSE:',metrics(actual,naive))
    print('Forecast moving-average MAE/RMSE:',metrics(actual,moving))
    print('Independent extensions: add an outlier; change costs; compare horizons; identify which assumptions fail before reusing a formula.')

if __name__=='__main__':
    run()