Practice Free
MediumJoins

Drug-Allergy Interaction Warning Join

Frequently Asked By:AppleGoogleAmazon
Interactive In-Browser Workspace

Practice this problem on live schema tables in PostgreSQL 16 WASM with instant row verification and visual EXPLAIN plans.

Solve in Workbench

Problem Statement

Join `prescriptions` with `patient_allergies` where the prescription's `active_ingredient` matches the patient's recorded `allergen_substance` for the same patient (`p.patient_id = a.patient_id`). Return: 1. `p.prescription_id` 2. `p.patient_id` 3. `p.medication_name` 4. `a.allergen_substance` 5. `a.severity` Order results by `p.prescription_id` ascending.

Why Technical Interviewers Ask This

Patient safety software automatically flags orders when a physician prescribes a medication containing an active chemical ingredient matching a recorded patient allergy.

Common Pitfalls & Interview Traps

Forgetting required sorting and deterministic tie-breaking.
Not accounting for NULL or zero-value denominators during calculations.
Using inefficient quadratic subqueries instead of single-pass joins constructs.

Canonical Modern SQL Solution

PostgreSQL 16 / ANSI SQL
SELECT 
        p.prescription_id,
        p.patient_id,
        p.medication_name,
        a.allergen_substance,
        a.severity
      FROM prescriptions p
      JOIN patient_allergies a ON p.patient_id = a.patient_id AND p.active_ingredient = a.allergen_substance
      ORDER BY p.prescription_id ASC;
Approach Breakdown
This query addresses the problem requirements by filtering and structuring data in Joins. It meets the target criteria: Flagged prescriptions where prescribed drug substance matches documented patient allergies.

Edge Cases to Verbally Clarify with Your Interviewer

The dataset contains zero matching records (must return valid empty result without crashing).
Multiple records tie on sorting criteria (must evaluate tie-breaking order deterministically).
Foreign keys or secondary attributes have NULL values.

Frequently Asked Follow-Up Questions

What makes this question a favorite among Apple and Google interviewers?

Interviewers use this problem to test whether candidates write defensive, scalable Joins queries that run efficiently on multi-million row production databases without excessive memory usage.

How does the query optimizer execute this query?

Using single-pass table scans with index lookups or sort buffers. Running EXPLAIN (ANALYZE, BUFFERS) in the DB Exercises workbench visualizes the execution nodes and buffer hit cache.

More FAANG SQL Interview Questions

View all questions