Every modelling interview question ("design the database for a cab booking app") is answered the same way. Interviewers want to see the process as much as the final tables.
Step
What to do
1. Clarify scope
Which features? Which users? Scale (rows per day)? Transactions or analytics?
2. List entities
Nouns in the requirements: rider, driver, trip, payment
3. Relationships and cardinality
1:1, 1:N, M:N; resolve M:N with associative tables
4. Keys and constraints
Primary, foreign, unique, check; natural vs surrogate keys
5. Lifecycle and history
Status changes, events, SCD needs, soft deletes, audit
6. Access patterns
The top queries; indexes, partitioning, denormalisation
7. Analytics model
Facts at a declared grain, conformed dimensions
8. Edge cases
Concurrency, money and time zones, privacy, idempotency
The six case studies below follow these steps. Each OLTP schema was created and loaded with sample rows in DuckDB, and every query result shown is real.
2. Banking System
Scope: customers with KYC, accounts (savings, current, loan), joint accounts, deposits, transfers and withdrawals, statements. Non-negotiables: money is never created or lost, every change is auditable, retries never post twice.
Key design decisions
Double-entry ledger: each money movement is a journal entry with postings that sum to zero (debit one account, credit another). Balances are derived from postings, so they can always be proven
Joint accounts: customer and account are M:N, resolved by account_holder with a role
Idempotency key on each entry: a payment retried after a timeout is rejected by the UNIQUE constraint instead of debiting twice
DECIMAL for money, never floating point; currency stored with the account
Immutability: postings are never updated; corrections are reversing entries
CREATE TABLE customer (customer_id INT PRIMARY KEY, full_name VARCHAR NOT NULL, kyc_status VARCHAR NOT NULL,
date_of_birth DATE, created_at TIMESTAMP);
CREATE TABLE account (account_id INT PRIMARY KEY, account_type VARCHAR CHECK (account_type IN ('SAVINGS','CURRENT','LOAN')),
currency CHAR(3) NOT NULL, opened_on DATE, status VARCHAR NOT NULL);
CREATE TABLE account_holder (account_id INT REFERENCES account, customer_id INT REFERENCES customer,
role VARCHAR CHECK (role IN ('PRIMARY','JOINT')), PRIMARY KEY (account_id, customer_id));
-- double-entry ledger: every journal entry's postings sum to zero
CREATE TABLE journal_entry (entry_id INT PRIMARY KEY, posted_at TIMESTAMP NOT NULL, description VARCHAR,
idempotency_key VARCHAR UNIQUE NOT NULL); -- retries cannot post twice
CREATE TABLE posting (entry_id INT REFERENCES journal_entry, account_id INT REFERENCES account,
amount DECIMAL(18,2) NOT NULL, -- + credit, - debit
PRIMARY KEY (entry_id, account_id));
Every entry must balance, and balances are derived
SELECT entry_id, SUM(amount) AS must_be_zero FROM posting GROUP BY entry_id ORDER BY entry_id;
entry_id
must_be_zero
1
0.00
2
0.00
3
0.00
-- WRONG: holders joined before summing
SELECT a.account_id, a.account_type, SUM(p.amount) AS balance,
STRING_AGG(c.full_name || ' (' || h.role || ')', ', ' ORDER BY h.role DESC) AS holders
FROM account a
JOIN posting p USING (account_id)
JOIN account_holder h USING (account_id)
JOIN customer c USING (customer_id)
WHERE a.account_id <> 9000
GROUP BY a.account_id, a.account_type ORDER BY a.account_id;
This version is wrong: joint account 2000 has two holders, so its single 20,000 posting is counted twice (40,000), and Asha is listed once per posting on account 1000. It is the same fan-out problem as joining two fact tables. Aggregate the postings first, then attach the holders:
-- RIGHT: sum postings per account first, then attach holders
WITH bal AS (SELECT account_id, SUM(amount) AS balance FROM posting GROUP BY account_id)
SELECT b.account_id, b.balance,
(SELECT STRING_AGG(c.full_name, ', ') FROM account_holder h JOIN customer c USING (customer_id)
WHERE h.account_id = b.account_id) AS holders
FROM bal b WHERE b.account_id <> 9000 ORDER BY b.account_id;
account_id
balance
holders
1000
25,000.00
Asha Rao
2000
20,000.00
Asha Rao, Ravi Kumar
Analytics model
Table
Type and grain
fact_transaction
Transaction fact: one row per posting (account, date, channel, amount)
fact_daily_balance
Periodic snapshot: one row per account per day (semi-additive balance)
dim_customer
SCD2 (segment, KYC status, address over time)
dim_account, dim_date, dim_channel, dim_branch
Conformed dimensions
Say this in the interview
"For banking I use a double-entry ledger: journal entries whose postings sum to zero, balances derived from postings, immutable rows with reversing entries for corrections, DECIMAL money, and an idempotency key so retries never post twice. Joint accounts are M:N through account_holder. Analytics uses a transaction fact plus a daily balance snapshot, with SCD2 customers."
3. Cab Booking Platform
Scope: riders request trips, drivers accept, trips move through statuses, fares include surge pricing, payments and ratings. Scale: millions of trips a day and GPS pings every few seconds, which do not belong in the OLTP database.
Key design decisions
Trip lifecycle: the current status and milestone timestamps live on trip; every transition is also appended to trip_event for audit and analytics
GPS pings go to a stream (Kafka) and a time-series or lake store, not the OLTP database; only pickup, drop and route summary are kept on the trip
Surge multiplier and fare are stored on the trip at booking time, never recomputed from current pricing
One payment per trip (UNIQUE trip_id); refunds as separate records
Zones as a dimension (often H3 hexagons) for pricing and supply-demand analytics
CREATE TABLE rider (rider_id INT PRIMARY KEY, name VARCHAR, phone VARCHAR UNIQUE, rating DECIMAL(3,2));
CREATE TABLE driver (driver_id INT PRIMARY KEY, name VARCHAR, licence_no VARCHAR UNIQUE, rating DECIMAL(3,2));
CREATE TABLE vehicle (vehicle_id INT PRIMARY KEY, driver_id INT REFERENCES driver, category VARCHAR, plate VARCHAR UNIQUE);
CREATE TABLE zone (zone_id INT PRIMARY KEY, city VARCHAR, name VARCHAR);
CREATE TABLE trip (trip_id INT PRIMARY KEY, rider_id INT REFERENCES rider, driver_id INT REFERENCES driver,
pickup_zone INT REFERENCES zone, drop_zone INT REFERENCES zone,
status VARCHAR CHECK (status IN ('REQUESTED','ACCEPTED','STARTED','COMPLETED','CANCELLED')),
requested_at TIMESTAMP, accepted_at TIMESTAMP, started_at TIMESTAMP, completed_at TIMESTAMP,
surge_multiplier DECIMAL(3,2) DEFAULT 1.0, fare DECIMAL(10,2), distance_km DECIMAL(6,2));
CREATE TABLE trip_event (trip_id INT REFERENCES trip, event_time TIMESTAMP, status VARCHAR, -- full status history
lat DECIMAL(9,6), lon DECIMAL(9,6));
CREATE TABLE payment (payment_id INT PRIMARY KEY, trip_id INT REFERENCES trip UNIQUE, method VARCHAR, amount DECIMAL(10,2), status VARCHAR);
Operational metrics
SELECT z.name AS pickup_zone,
COUNT(*) AS requests,
COUNT(*) FILTER (WHERE status = 'COMPLETED') AS completed,
ROUND(100.0 * COUNT(*) FILTER (WHERE status = 'CANCELLED') / COUNT(*), 1) AS cancel_pct,
ROUND(AVG(DATE_DIFF('minute', requested_at, started_at)), 1) AS avg_wait_min,
ROUND(AVG(fare / distance_km), 1) AS fare_per_km
FROM trip t JOIN zone z ON z.zone_id = t.pickup_zone
GROUP BY z.name ORDER BY requests DESC;
pickup_zone
requests
completed
cancel_pct
avg_wait_min
fare_per_km
Airport
3
2
33.3
12.5
24.3
Hinjewadi
1
1
0.0
10.0
21.4
Koregaon Park
1
0
100.0
NULL
NULL
SELECT d.name AS driver,
COUNT(*) FILTER (WHERE t.status = 'COMPLETED') AS trips,
SUM(t.fare) AS earnings,
ROUND(SUM(t.distance_km), 1) AS km
FROM driver d LEFT JOIN trip t ON t.driver_id = d.driver_id
GROUP BY d.name ORDER BY earnings DESC;
driver
trips
earnings
km
Leela
2
780.00
35.00
Kiran
1
540.00
21.00
Analytics model
Table
Type and grain
fact_trip
Accumulating snapshot: one row per trip with requested, accepted, started, completed timestamps and durations between them
fact_trip_event
Transaction fact: one row per status change
fact_driver_hour
Periodic snapshot: online minutes, trips, earnings per driver per hour
"A trip has a status lifecycle, so I keep current status and milestone timestamps on the trip and append every transition to a trip_event table. Fares and surge are frozen at booking. GPS pings go to a stream and the lake, not the OLTP database. For analytics, fact_trip is an accumulating snapshot, zone is a role-playing dimension for pickup and drop, and I add an hourly driver snapshot for supply metrics."
4. E-commerce Platform
Scope: catalogue with variants, inventory per warehouse, carts, orders, payments, shipments, returns and reviews. Traps: prices change, addresses change, products have variants, returns are partial.
Key design decisions
Product vs SKU: a product ("Linen Shirt") has sellable variants (size M white) with their own price and stock
Snapshot values at order time: unit price, discount and shipping address are copied onto the order, so history never changes when the catalogue does
Category tree via a self-referencing parent_id (query with a recursive CTE)
Inventory per SKU per warehouse with a non-negative check; reservations decrement stock atomically
Returns at line level with quantity and refund amount, so partial returns are exact
CREATE TABLE customer (customer_id INT PRIMARY KEY, email VARCHAR UNIQUE NOT NULL, created_at TIMESTAMP);
CREATE TABLE category (category_id INT PRIMARY KEY, name VARCHAR, parent_id INT); -- tree: parent_id -> category_id
CREATE TABLE product (product_id INT PRIMARY KEY, name VARCHAR, category_id INT REFERENCES category, brand VARCHAR);
CREATE TABLE sku (sku_id INT PRIMARY KEY, product_id INT REFERENCES product, size VARCHAR, colour VARCHAR,
list_price DECIMAL(10,2) NOT NULL); -- sellable variant
CREATE TABLE inventory (sku_id INT REFERENCES sku, warehouse VARCHAR, on_hand INT CHECK (on_hand >= 0),
PRIMARY KEY (sku_id, warehouse));
CREATE TABLE orders (order_id INT PRIMARY KEY, customer_id INT REFERENCES customer, ordered_at TIMESTAMP,
status VARCHAR, shipping_address VARCHAR); -- address copied at order time
CREATE TABLE order_item (order_id INT REFERENCES orders, line_no INT, sku_id INT REFERENCES sku, qty INT CHECK (qty > 0),
unit_price DECIMAL(10,2) NOT NULL, discount DECIMAL(10,2) DEFAULT 0, -- price charged
PRIMARY KEY (order_id, line_no));
CREATE TABLE return_item (order_id INT, line_no INT, returned_qty INT, reason VARCHAR, refunded DECIMAL(10,2),
FOREIGN KEY (order_id, line_no) REFERENCES order_item (order_id, line_no));
Net revenue by top-level category, after returns
WITH RECURSIVE tree AS (
SELECT category_id, name AS top_category FROM category WHERE parent_id IS NULL
UNION ALL
SELECT c.category_id, t.top_category FROM category c JOIN tree t ON c.parent_id = t.category_id
),
lines AS (
SELECT oi.order_id, oi.line_no, p.category_id,
oi.qty * oi.unit_price - oi.discount AS gross,
COALESCE(r.refunded, 0) AS refunded
FROM order_item oi
JOIN sku s USING (sku_id) JOIN product p USING (product_id)
LEFT JOIN return_item r USING (order_id, line_no)
)
SELECT t.top_category, SUM(gross) AS gross, SUM(refunded) AS refunds, SUM(gross - refunded) AS net
FROM lines l JOIN tree t USING (category_id)
GROUP BY t.top_category ORDER BY net DESC;
top_category
gross
refunds
net
Fashion
5,900.00
1,100.00
4,800.00
Electronics
2,600.00
0.00
2,600.00
SELECT s.sku_id, p.name, s.size, SUM(i.on_hand) AS on_hand,
CASE WHEN SUM(i.on_hand) = 0 THEN 'OUT OF STOCK' ELSE 'available' END AS status
FROM sku s JOIN product p USING (product_id) JOIN inventory i USING (sku_id)
GROUP BY s.sku_id, p.name, s.size ORDER BY s.sku_id;
sku_id
name
size
on_hand
status
100
Linen Shirt
M
40
available
101
Linen Shirt
L
0
OUT OF STOCK
102
Summer Dress
S
12
available
103
Earbuds
NULL
25
available
Analytics model
Table
Type and grain
fact_order_line
One row per order line: qty, gross, discount, tax, net
fact_return_line
One row per returned line (combine with sales via drill-across, not a direct join)
fact_inventory_daily
Periodic snapshot per SKU per warehouse per day
fact_web_session
Funnel: views, add-to-cart, checkout, purchase
dim_product (SCD2 on category, brand), dim_customer, dim_date, dim_warehouse, dim_promotion
Dimensions
Say this in the interview
"I separate product from SKU, keep inventory per SKU per warehouse, model categories as a tree, and snapshot price, discount and address on the order line so history never changes. Returns are line-level for partial refunds. Analytics has an order-line fact, a return fact combined by drill-across, a daily inventory snapshot and a web funnel fact."
5. Video Streaming Service
Scope: accounts with subscription plans, several profiles per account, a catalogue of movies and series with seasons and episodes, genres, and playback. Scale: playback emits heartbeat events every few seconds for millions of concurrent streams, so viewing data is modelled for the lakehouse, not the OLTP database.
Key design decisions
Account vs profile: billing belongs to the account, viewing and recommendations to the profile
Subscription history with validity dates, so revenue and churn can be computed for any month
Title → episode hierarchy; a movie is a title with one playable item, which keeps playback uniform
Genres are M:N through title_genre
Playback: raw heartbeats stream to Kafka and the lake; a sessionisation job aggregates them into one row per playback session
CREATE TABLE account (account_id INT PRIMARY KEY, email VARCHAR UNIQUE, country CHAR(2), created_at DATE);
CREATE TABLE plan (plan_id INT PRIMARY KEY, name VARCHAR, max_streams INT, monthly_price DECIMAL(8,2));
CREATE TABLE subscription (account_id INT REFERENCES account, plan_id INT REFERENCES plan,
valid_from DATE, valid_to DATE, PRIMARY KEY (account_id, valid_from)); -- plan history
CREATE TABLE profile (profile_id INT PRIMARY KEY, account_id INT REFERENCES account, name VARCHAR, is_kids BOOLEAN);
CREATE TABLE title (title_id INT PRIMARY KEY, name VARCHAR, title_type VARCHAR CHECK (title_type IN ('MOVIE','SERIES')),
release_year INT, maturity_rating VARCHAR);
CREATE TABLE episode (episode_id INT PRIMARY KEY, title_id INT REFERENCES title, season INT, episode_no INT, runtime_min INT);
CREATE TABLE genre (genre_id INT PRIMARY KEY, name VARCHAR);
CREATE TABLE title_genre (title_id INT REFERENCES title, genre_id INT REFERENCES genre, PRIMARY KEY (title_id, genre_id));
-- high-volume events: in production these stream to Kafka and the lakehouse, partitioned by date
CREATE TABLE playback_session (session_id VARCHAR PRIMARY KEY, profile_id INT REFERENCES profile,
episode_id INT REFERENCES episode, device VARCHAR,
started_at TIMESTAMP, watched_min INT);
Completion rate per title, and binge sessions
SELECT t.name, COUNT(*) AS plays, SUM(ps.watched_min) AS minutes,
ROUND(100.0 * AVG(LEAST(ps.watched_min::DOUBLE / e.runtime_min, 1)), 1) AS avg_completion_pct
FROM playback_session ps
JOIN episode e USING (episode_id) JOIN title t USING (title_id)
GROUP BY t.name ORDER BY minutes DESC;
name
plays
minutes
avg_completion_pct
Data Heist
4
140
70.4
The Pipeline
1
40
33.9
Ocean Tales
1
25
100.0
-- a binge: consecutive episodes of one series within 15 minutes of the previous one ending
WITH s AS (
SELECT p.name AS profile, t.name AS title, ps.started_at, ps.watched_min,
LAG(ps.started_at + INTERVAL (ps.watched_min) MINUTE)
OVER (PARTITION BY ps.profile_id, e.title_id ORDER BY ps.started_at) AS prev_end
FROM playback_session ps JOIN episode e USING (episode_id) JOIN title t USING (title_id)
JOIN profile p USING (profile_id)
)
SELECT profile, title, COUNT(*) + 1 AS episodes_in_a_row
FROM s
WHERE started_at - prev_end <= INTERVAL 15 MINUTE
GROUP BY profile, title;
profile
title
episodes_in_a_row
Asha
Data Heist
3
Analytics model
Table
Type and grain
fact_playback_session
One row per session: profile, episode, device, minutes, completion
fact_subscription_month
Periodic snapshot: one row per account per month (plan, MRR, churn flag)
fact_title_daily
Aggregate: views and minutes per title per country per day
dim_title (with bridge to genres), dim_profile, dim_device, dim_date, dim_country
Dimensions; genre is multi-valued, handled with a bridge table
Say this in the interview
"I split account (billing) from profile (viewing), keep subscription history with validity dates for revenue and churn, model title to episode as a hierarchy and genres as M:N. Playback heartbeats are too voluminous for OLTP, so they stream to the lakehouse and are sessionised into a playback-session fact, used for completion rates, binge analysis and recommendations."
6. Online Learning Platform
Scope: an upskilling platform with a structured program (modules and lessons), cohorts, mentors, progress tracking, assessments and mock interviews. Questions the business asks: where do learners drop off, which mentors are overloaded, how do assessment scores relate to interview performance?
Key design decisions
Program → module → lesson hierarchy with sequence numbers, and a program version, because the curriculum changes over time
Cohort (a batch starting on a date) between learner and program, so the same program can run many times
Enrolment carries the mentor and a status lifecycle (active, paused, completed, dropped)
lesson_progress with a composite key: one completion per learner per lesson, with an optional score
Mentor capacity stored so assignments can be checked against it
CREATE TABLE learner (learner_id INT PRIMARY KEY, name VARCHAR, email VARCHAR UNIQUE, experience_years INT);
CREATE TABLE mentor (mentor_id INT PRIMARY KEY, name VARCHAR, company VARCHAR, max_learners INT);
CREATE TABLE program (program_id INT PRIMARY KEY, name VARCHAR, version INT); -- versioned curriculum
CREATE TABLE module (module_id INT PRIMARY KEY, program_id INT REFERENCES program, seq INT, name VARCHAR);
CREATE TABLE lesson (lesson_id INT PRIMARY KEY, module_id INT REFERENCES module, seq INT, name VARCHAR, kind VARCHAR);
CREATE TABLE cohort (cohort_id INT PRIMARY KEY, program_id INT REFERENCES program, start_date DATE);
CREATE TABLE enrolment (learner_id INT REFERENCES learner, cohort_id INT REFERENCES cohort, mentor_id INT REFERENCES mentor,
status VARCHAR CHECK (status IN ('ACTIVE','PAUSED','COMPLETED','DROPPED')),
enrolled_on DATE, PRIMARY KEY (learner_id, cohort_id));
CREATE TABLE lesson_progress (learner_id INT, lesson_id INT REFERENCES lesson, completed_at TIMESTAMP,
score INT, PRIMARY KEY (learner_id, lesson_id));
CREATE TABLE mock_interview (interview_id INT PRIMARY KEY, learner_id INT, mentor_id INT, held_on DATE,
topic VARCHAR, rating INT CHECK (rating BETWEEN 1 AND 5));
Progress funnel by module
SELECT m.seq, m.name AS module,
COUNT(DISTINCT lp.learner_id) AS learners_started,
ROUND(100.0 * COUNT(lp.lesson_id) /
(COUNT(DISTINCT l.lesson_id) * (SELECT COUNT(*) FROM enrolment)), 1) AS completion_pct
FROM module m
JOIN lesson l USING (module_id)
LEFT JOIN lesson_progress lp USING (lesson_id)
GROUP BY m.seq, m.name ORDER BY m.seq;
seq
module
learners_started
completion_pct
1
Programming
3
77.8
2
Fundamentals
2
50.0
3
Tools
1
33.3
SELECT me.name AS mentor, me.max_learners,
COUNT(DISTINCT e.learner_id) AS assigned, -- DISTINCT: mocks multiply rows
ROUND(AVG(mi.rating), 1) AS avg_mock_rating,
COUNT(mi.interview_id) AS mocks_held
FROM mentor me
LEFT JOIN enrolment e ON e.mentor_id = me.mentor_id
LEFT JOIN mock_interview mi ON mi.mentor_id = me.mentor_id AND mi.learner_id = e.learner_id
GROUP BY me.name, me.max_learners ORDER BY me.name;
mentor
max_learners
assigned
avg_mock_rating
mocks_held
Arjun
3
2
4.0
3
Pooja
3
1
NULL
0
Analytics model
Table
Type and grain
fact_lesson_completion
One row per learner per lesson completed (with score)
fact_learner_week
Periodic snapshot: progress %, active days, status per learner per week
fact_mock_interview
One row per mock interview with rating
dim_learner, dim_mentor, dim_lesson (with module and program version), dim_cohort, dim_date
Dimensions
Say this in the interview
"I model program, module and lesson as a versioned hierarchy, cohorts as runs of a program, and enrolment as the learner-cohort link carrying mentor and status. Progress is one row per learner per lesson. Analytics uses a completion fact and a weekly learner snapshot to find drop-off points and correlate assessment scores with mock interview ratings."
7. Hospital Network
Scope: several hospitals with departments, doctors, patients, appointments, admissions with beds, diagnoses coded in ICD-10, billing and insurance claims. Constraints: patient data is highly sensitive health information, regulated by laws such as India's DPDP Act, HIPAA in the US and GDPR in Europe.
Key design decisions
Patient identity: one patient across all branches, identified by a medical record number (MRN); MDM to merge duplicates from different branches
Coded clinical data: diagnoses as ICD-10 codes, not free text, so they can be analysed; one primary diagnosis per admission
Admission as an episode with admitted and discharged timestamps; NULL discharge means still admitted
Privacy by design: personal identifiers kept in the patient table only, column-level masking, access by role and purpose, full audit of reads
Analytics on pseudonymised data: facts use a surrogate patient key; names and phone numbers never reach the warehouse
CREATE TABLE hospital (hospital_id INT PRIMARY KEY, name VARCHAR, city VARCHAR);
CREATE TABLE department (dept_id INT PRIMARY KEY, hospital_id INT REFERENCES hospital, name VARCHAR);
CREATE TABLE doctor (doctor_id INT PRIMARY KEY, name VARCHAR, specialty VARCHAR, dept_id INT REFERENCES department);
CREATE TABLE patient (patient_id INT PRIMARY KEY, mrn VARCHAR UNIQUE, -- medical record number
full_name VARCHAR, date_of_birth DATE, phone VARCHAR); -- PHI: restricted access
CREATE TABLE bed (bed_id INT PRIMARY KEY, dept_id INT REFERENCES department, ward VARCHAR, bed_type VARCHAR);
CREATE TABLE appointment (appointment_id INT PRIMARY KEY, patient_id INT REFERENCES patient, doctor_id INT REFERENCES doctor,
scheduled_at TIMESTAMP, status VARCHAR CHECK (status IN ('BOOKED','COMPLETED','NO_SHOW','CANCELLED')));
CREATE TABLE admission (admission_id INT PRIMARY KEY, patient_id INT REFERENCES patient, hospital_id INT REFERENCES hospital,
bed_id INT REFERENCES bed, attending_doctor INT REFERENCES doctor,
admitted_at TIMESTAMP NOT NULL, discharged_at TIMESTAMP, discharge_type VARCHAR);
CREATE TABLE diagnosis (admission_id INT REFERENCES admission, icd10_code VARCHAR, is_primary BOOLEAN,
PRIMARY KEY (admission_id, icd10_code));
CREATE TABLE bill (bill_id INT PRIMARY KEY, admission_id INT REFERENCES admission, total DECIMAL(12,2),
insurer VARCHAR, claim_status VARCHAR);
Average length of stay and 30-day readmissions
SELECT h.name AS hospital,
COUNT(*) AS admissions,
ROUND(AVG(DATE_DIFF('hour', admitted_at, discharged_at)) / 24.0, 1) AS avg_los_days,
COUNT(*) FILTER (WHERE discharged_at IS NULL) AS currently_admitted
FROM admission a JOIN hospital h USING (hospital_id)
GROUP BY h.name ORDER BY h.name;
hospital
admissions
avg_los_days
currently_admitted
City Hospital North
3
4.6
1
City Hospital South
1
2.0
0
WITH ordered AS (
SELECT patient_id, admission_id, admitted_at, discharged_at,
LEAD(admitted_at) OVER (PARTITION BY patient_id ORDER BY admitted_at) AS next_admission
FROM admission
)
SELECT 'P' || LPAD(CAST(patient_id AS VARCHAR), 4, '0') AS patient_ref, -- pseudonymised in output
admission_id, discharged_at::DATE AS discharged,
next_admission::DATE AS readmitted,
DATE_DIFF('day', discharged_at, next_admission) AS days_between
FROM ordered
WHERE next_admission IS NOT NULL AND next_admission <= discharged_at + INTERVAL 30 DAY;
patient_ref
admission_id
discharged
readmitted
days_between
P0001
1
2026-02-06
2026-02-20
14
SELECT d.name AS department, COUNT(b.bed_id) AS beds,
COUNT(a.admission_id) AS occupied_now,
ROUND(100.0 * COUNT(a.admission_id) / COUNT(b.bed_id), 0) AS occupancy_pct
FROM department d
JOIN bed b USING (dept_id)
LEFT JOIN admission a ON a.bed_id = b.bed_id AND a.discharged_at IS NULL
GROUP BY d.name ORDER BY d.name;
department
beds
occupied_now
occupancy_pct
Cardiology
2
0
0.0
General Medicine
1
1
100.0
Orthopaedics
1
0
0.0
Analytics model
Table
Type and grain
fact_admission
Accumulating snapshot: one row per admission with admit, discharge, length of stay, cost, readmission flag
fact_appointment
One row per appointment with status (no-show analysis)
fact_bed_daily
Periodic snapshot: occupancy per bed per day
bridge_admission_diagnosis
Multi-valued diagnoses per admission
dim_patient (pseudonymised, age band not birth date), dim_doctor, dim_department, dim_hospital, dim_diagnosis (ICD-10 hierarchy), dim_date
Dimensions
Say this in the interview
"A hospital model centres on the patient, identified across branches by an MRN, with admissions as episodes, ICD-10 coded diagnoses through a bridge, beds and billing. Privacy drives the design: identifiers stay in one restricted table, analytics uses pseudonymised keys and age bands, and access is audited. Key metrics like length of stay, 30-day readmission and bed occupancy come from an admission accumulating snapshot and a daily bed snapshot."