Portfolio laboratory

SQL projects

Decision-ready analysis built from relational data, clear definitions and reproducible queries.

All datasets and commercial scenarios on this page are synthetic and created for portfolio demonstration.

Choose a case.

Each case includes the business question, source structure, working method, selected code or decision logic, measured result, recommendation and limitations.

Major synthetic case studySQL

Working-capital & receivables decision system

Which collection actions release cash without confusing ageing with customer risk?

A full SQL control layer for invoice validation, weighted DSO, ageing, concentration, dispute exposure, collector capacity and payment-term scenarios.

372-line SQL system · controls · DSO · ageing · collection queue · term scenarios

£49.2m
open receivables
56.6%
overdue share
£12.6m
top-100 action value
View full case study
Synthetic case studySQL

Retail margin & discount leakage

Which sales look healthy until discount and cost are included?

A reproducible gross-margin diagnostic that separates top-line growth from value-destructive discounting and identifies where commercial controls should change.

£463k
analysed revenue
40.6%
gross margin
33.7%
margin on 15%+ discount orders
View full case study
Synthetic case studySQL

Tender pipeline & bid/no-bid analysis

Where should a constrained bid team spend its next week?

A bid-performance model that turns a pipeline list into a decision queue and separates attractive opportunities from expensive distractions.

36.8%
submitted-bid win rate
£92.2m
open pipeline
19.9d
average submission window
View full case study
Case 01
Major synthetic case study8,500 invoices · 720 customersSQL · Window functions · AR ageing · Scenario analysis

Working-capital & receivables decision system

Which collection actions release cash without confusing ageing with customer risk?

A full SQL control layer for invoice validation, weighted DSO, ageing, concentration, dispute exposure, collector capacity and payment-term scenarios.

£49.2m
open receivables
56.6%
overdue share
£12.6m
top-100 action value

Business context

Finance has 8,500 invoices but no shared definition of open, overdue, disputed or high-priority cash. The project builds the control layer before ranking collection activity.

Questions tested

  1. What open receivable value reconciles to the invoice population?
  2. How do ageing, credit risk, dispute and concentration change the collection priority?
  3. Which actions fit collector capacity and what payment-term scenarios deserve testing?

Working method

From raw information to a decision.

  1. 01

    Validated invoice identity, dates, amounts and controlled risk values before any aggregation.

  2. 02

    Created one governed status and ageing view using the reporting snapshot rather than the current clock.

  3. 03

    Calculated weighted DSO, ageing, customer concentration and disputed exposure without averaging ratios.

  4. 04

    Built an invoice-level action score and separate owner rank so the queue remains usable under capacity constraints.

  5. 05

    Modelled term and dispute-resolution scenarios and retained a final reconciliation query for executive reporting.

Dataset

Visible grain, fields and sample.

invoice_id / customer_idUnique document and customer grain
issue_date / due_dateContractual ageing baseline
payment_dateObserved settlement date; blank when open
invoice_amount_gbpReceivable value
credit_riskLow, medium or high controlled rating
dispute_flagKnown collection dependency
account_ownerNamed operating follow-up owner
InvoiceCustomerSegmentRiskIssuedDueAmount
INV-000001AR-0580SMELow19 Aug 202518 Sep 2025£16,850
INV-000002AR-0042EnterpriseLow22 Dec 202520 Feb 2026£40,300
INV-000003AR-0335EnterpriseMedium24 Jan 202523 Feb 2025£74,168

Preview shows three records; the complete synthetic dataset is available above.

Selected workingSQL
WITH open_invoices AS (
  SELECT *,
    CASE credit_risk WHEN 'High' THEN 1.30
      WHEN 'Medium' THEN 1.12 ELSE 1.00 END AS risk_weight,
    CASE WHEN dispute_flag = 1 THEN 0.72 ELSE 1.00 END AS collectability,
    CASE WHEN days_past_due >= 91 THEN 1.65
      WHEN days_past_due >= 61 THEN 1.45
      WHEN days_past_due >= 31 THEN 1.25
      WHEN days_past_due >= 1 THEN 1.08 ELSE 0.35 END AS lateness_weight
  FROM ar_status WHERE payment_date IS NULL
)
SELECT *,
  invoice_amount_gbp * risk_weight * collectability * lateness_weight AS action_score,
  DENSE_RANK() OVER (PARTITION BY account_owner
    ORDER BY invoice_amount_gbp * risk_weight * collectability * lateness_weight DESC) AS owner_rank
FROM open_invoices;

Result

Not due£21.36m
90+ days£10.19m
1-30 days£9.51m
31-60 days£6.35m
61-90 days£1.80m
  • The reconciled snapshot contained £49.21m of open receivables; £27.85m (56.6%) was overdue.
  • £10.19m sat beyond 90 days and £4.57m of open value was disputed, requiring different action from routine reminders.
  • Weighted paid-invoice DSO was 50.4 days. The top 25 customers represented 21.2% of open exposure.
  • The top 100 risk-weighted invoice actions represented £12.57m—enough concentration to make a bounded daily queue commercially meaningful.

Recommendation

Publish one reconciled ageing view, assign the top 20 actions per owner and separate dispute resolution from ordinary collections. Review concentration and weighted DSO monthly, then test term changes only where customer economics support them.

Limits & next evidence

The synthetic case has no credit notes, partial payments, promise-to-pay history, customer profitability or legal status. A production queue must incorporate those controls and must not use risk labels without governance.

Case 02
Synthetic case study2,400 transactionsSQL · CTEs · Window functions · KPI design

Retail margin & discount leakage

Which sales look healthy until discount and cost are included?

A reproducible gross-margin diagnostic that separates top-line growth from value-destructive discounting and identifies where commercial controls should change.

£463k
analysed revenue
40.6%
gross margin
33.7%
margin on 15%+ discount orders

Business context

A multi-channel retailer sees revenue growth but no equivalent improvement in profit. The analysis tests whether discount behaviour, channel mix or regional product mix explains the gap.

Questions tested

  1. How do revenue and gross-margin percentage change across discount bands?
  2. Which high-revenue segments sit in the bottom of their region for margin?
  3. Where should a commercial manager introduce approval thresholds?

Working method

From raw information to a decision.

  1. 01

    Defined gross margin as revenue less direct product cost and reconciled it to the transaction total.

  2. 02

    Built discount bands and segment roll-ups with CTEs.

  3. 03

    Used NTILE and DENSE_RANK to separate commercially material leakage from small outliers.

  4. 04

    Created a monthly control view for repeatable management reporting.

Dataset

Visible grain, fields and sample.

transaction_idUnique order-line key
region / channelCommercial segmentation
discount_pctApplied selling discount
revenue_gbpNet sales after discount
cogs_gbpDirect product cost
gross_margin_gbpRevenue less cost of goods
IDRegionChannelProductDiscountRevenueMargin
TX-00001NorthMarketplaceWireless Headset0%£189.24£92.12
TX-00002MidlandsWebYoga Mat0%£110.70£64.08
TX-00003MidlandsMarketplaceAir Fryer10%£110.01£39.23

Preview shows three records; the complete synthetic dataset is available above.

Selected workingSQL
WITH segment_performance AS (
  SELECT region, channel, product,
         SUM(revenue_gbp) AS revenue_gbp,
         100.0 * SUM(gross_margin_gbp)
           / NULLIF(SUM(revenue_gbp), 0) AS margin_pct
  FROM retail_margin_transactions
  GROUP BY region, channel, product
), ranked AS (
  SELECT *,
         NTILE(4) OVER (ORDER BY revenue_gbp DESC) AS revenue_quartile,
         DENSE_RANK() OVER
           (PARTITION BY region ORDER BY margin_pct) AS margin_risk_rank
  FROM segment_performance
)
SELECT * FROM ranked
WHERE revenue_quartile = 1 AND margin_risk_rank <= 3;

Result

South41.1%
North41.0%
Midlands40.5%
London40.0%
  • The portfolio generated £463,479 of revenue at a 40.6% blended gross margin.
  • Orders discounted by 15% or more fell to 33.7% margin, a 6.9-point gap to the portfolio average.
  • London had the weakest regional margin at 40.0%; Ergonomic Chair generated the most total gross margin.

Recommendation

Require commercial approval for discounts at or above 15%, then review the high-revenue/low-margin segment queue weekly. Test channel-specific floors rather than imposing one blanket target.

Limits & next evidence

The model includes product cost but not fulfilment, returns, customer lifetime value or price elasticity. A live pricing decision should incorporate those economics and run a controlled test.

Case 03
Synthetic case study320 tender recordsSQL · Funnel analysis · Risk segmentation · Scenario logic

Tender pipeline & bid/no-bid analysis

Where should a constrained bid team spend its next week?

A bid-performance model that turns a pipeline list into a decision queue and separates attractive opportunities from expensive distractions.

36.8%
submitted-bid win rate
£92.2m
open pipeline
19.9d
average submission window

Business context

A small infrastructure bid team cannot pursue every opportunity. The case converts a flat tender list into a transparent bid, qualify or no-bid decision queue.

Questions tested

  1. Which sectors have historically converted submitted bids most effectively?
  2. How should value, probability, cost, time pressure and delivery risk affect priority?
  3. Which high-risk no-bid decisions deserve a learning review?

Working method

From raw information to a decision.

  1. 01

    Separated open, no-bid and submitted outcomes so the win-rate denominator remained valid.

  2. 02

    Estimated sector-level base win probabilities from completed bids.

  3. 03

    Applied transparent penalties for competition and risk rather than a black-box score.

  4. 04

    Converted expected value and bid effort into a ranked action queue.

Dataset

Visible grain, fields and sample.

estimated_value_gbp_mIndicative contract value, £m
bid_cost_gbpInternal/external pursuit cost
days_to_submitRemaining response window
risk_score0–100 delivery and compliance risk
competitor_countExpected credible bidders
outcomeOpen, Won, Lost or No Bid
TenderSectorValueBid costDaysRiskOutcome
TN-0001Power£13.05m£12,5001649Lost
TN-0002Industrial EPC£14.53m£27,2503342Lost
TN-0003Smart City£0.70m£3,5003064Lost

Preview shows three records; the complete synthetic dataset is available above.

Selected workingSQL
WITH sector_history AS (
  SELECT sector,
    AVG(CASE WHEN outcome = 'Won' THEN 1.0 ELSE 0.0 END)
      FILTER (WHERE outcome IN ('Won', 'Lost')) AS base_probability
  FROM tender_pipeline GROUP BY sector
), scored AS (
  SELECT t.*,
    estimated_value_gbp_m * GREATEST(0.05,
      base_probability
      - GREATEST(competitor_count - 5, 0) * 0.012
      - GREATEST(risk_score - 60, 0) * 0.002
    ) AS expected_value_gbp_m
  FROM tender_pipeline t JOIN sector_history USING (sector)
  WHERE outcome = 'Open'
)
SELECT * FROM scored ORDER BY expected_value_gbp_m DESC;

Result

Power47.8%
Solar41.5%
Smart City36.8%
Telecom35.1%
Industrial EPC24.5%
  • The valid submitted-bid population was 266, producing a 36.8% historical win rate.
  • Power converted best at 47.8%, while Industrial EPC converted at 24.5%.
  • Open opportunities represented £92.2m of indicative pipeline; the historical submission window averaged 19.9 days.

Recommendation

Use the score as a triage aid, not an automatic decision. Mobilise high-value near-term bids, challenge high-risk work in a no-bid review, and capture the actual reason whenever judgement overrides the ranking.

Limits & next evidence

Contract value is not profit, and historical sector conversion may not represent buyer fit. A live model needs contribution margin, capacity, strategic account value and tender-specific qualification evidence.