Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 104

    Database Challenges

    Database mastery separates senior from junior backend engineers.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Database mastery separates senior from junior backend engineers. These challenges target Postgres skills you need for TechLearningPRO Orders: window functions, indexing with EXPLAIN, expand-contract migrations, soft delete with partial unique indexes, and audit triggers.

    Run everything against real Postgres (Testcontainers or local). Spring Data helps, but raw SQL literacy still wins outages.

    No fluff — each item has a deliverable query or migration.

    Purpose of this lesson

    Complete concrete Postgres challenges that show up in Orders reporting, migrations, and compliance.

    Understanding the topic

    Five skills — measure each with SQL output.

    • Window functions — top-10 monthly revenue report.
    • Indexing — turn a 4s query into ~40ms; prove with EXPLAIN.
    • Online DDL — expand-contract column type change without downtime.
    • Soft delete — partial unique indexes so active emails stay unique.
    • Audit triggers — record every change to a sensitive table.

    Step-by-step explanation

    1. Load a seed of ≥100k orders (script provided in your lab kit or generate).
    2. Write the report query; capture EXPLAIN ANALYZE before/after indexes.
    3. Practise expand-contract on amount_cents → larger numeric type in staging.
    4. Add soft-delete + audit trigger; verify with integration tests.

    Informative example

    Top-10 customers by month + partial unique soft delete.

    sql
    -- Top 10 customers by month (window functions)
    WITH monthly AS (
    SELECT date_trunc('month', created_at) AS month,
    customer_id,
    SUM(amount_cents) AS revenue_cents
    FROM orders
    WHERE deleted_at IS NULL
    GROUP BY 1, 2
    ), ranked AS (
    SELECT *, RANK() OVER (PARTITION BY month ORDER BY revenue_cents DESC) AS rnk
    FROM monthly
    )
    SELECT * FROM ranked WHERE rnk <= 10;
    -- Soft delete: email unique only among active rows
    CREATE UNIQUE INDEX uq_users_email_active
    ON users (email)
    WHERE deleted_at IS NULL;
    -- Index that fixes list-by-customer
    CREATE INDEX CONCURRENTLY idx_orders_customer_created
    ON orders (customer_id, created_at DESC);

    Real-world use

    Orders admin 'customers this month' timed out at 12s. EXPLAIN showed a sequential scan on 40M rows. A composite index on (customer_id, created_at) and a covering report materialized view dropped it to 35ms — exactly the indexing challenge.

    Security implications

    DB objects are part of the security boundary.

    • Audit tables should be append-only for the app role.
    • Do not grant DROP to the runtime DB user.
    • Connection credentials stay in env — never in migration comments.

    Best practices

    • Always EXPLAIN ANALYZE with production-like data volumes.
    • Keep Flyway/Liquibase migrations reviewable and reversible where possible.
    • Test triggers with an integration test that updates a row and asserts audit count.

    Common mistakes

    • Creating indexes without CONCURRENTLY on busy tables.
    • Unique constraints that break soft delete (deleted rows still collide).
    • Expand-contract half-finished — app still writing the old column only.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1IntermediateQuestionWhat is expand-contract?+

    Answer

    Add new column/structure, dual-write, backfill, switch reads, then remove old — so deploys stay online.
    2IntermediateQuestionWhy partial unique indexes for soft delete?+

    Answer

    They enforce uniqueness only for live rows, allowing historical duplicates after delete.
    3BeginnerQuestionWhen do window functions beat application-side ranking?+

    Answer

    When the dataset is large — push ranking to Postgres instead of loading all rows into the JVM.

    Hands-on exercise

    DB challenge pack. 1) Deliver the top-10 monthly SQL with sample output. 2) Show EXPLAIN ANALYZE before/after idx_orders_customer_created. 3) Write Flyway scripts for expand-contract renaming status_code varchar→enum-like check. 4) Soft-delete users with partial unique email index + tests. 5) Trigger orders_audit on UPDATE/DELETE; prove with SQL. Zip: .sql files + before/after plans.

    Summary

    Database challenges build Orders data seniority. Next: authentication challenges under Security 6.

    Ready to mark this lesson complete?Track your journey across the entire course.