w3resource

SQL Exercise: Patients who have had a procedure costing over $5,000

SQL hospital Database: Exercise-37 with Solution

37. From the following table, write a SQL query to find those patients who have undergone a procedure costing more than $5,000, as well as the name of the physician who has provided primary care, should be identified. Return name of the patient as "Patient", name of the physician as "Primary Physician", and cost for the procedure as "Procedure Cost".

Sample table: patient


Sample table: undergoes


Sample table: physician


Sample table: procedure


Sample Solution:


-- Selecting the name of the patient, primary physician, and procedure cost
SELECT pt.name AS " Patient ", -- Selecting the name column from the patient table and aliasing it as " Patient "
       p.name AS "Primary Physician", -- Selecting the name column from the physician table and aliasing it as "Primary Physician"
       pd.cost AS " Procedure Cost" -- Selecting the cost column from the procedure table and aliasing it as " Procedure Cost"
-- Joining patient table with undergoes table based on patient's SSN
FROM patient pt
JOIN undergoes u ON u.patient=pt.ssn
-- Joining patient table with physician table based on primary care physician's employee ID
JOIN physician p ON pt.pcp=p.employeeid
-- Joining undergoes table with procedure table based on procedure code
JOIN PROCEDURE pd ON u.procedure=pd.code
-- Filtering rows to include only those where the procedure cost is greater than 5000
WHERE pd.cost>5000;

Sample Output:

   Patient   | Primary Physician | Procedure Cost
------------+-------------------+----------------
 John Smith | John Dorian       |           5600
 Dennis Doe | Christopher Turk  |          10000
(2 rows)

Explanation:

The said query in SQL that selects the names of patients, their primary care physicians (PCPs), and the cost of any medical procedures undergone by the patient that cost more than 5,000.

The first JOIN statement joins the 'patient' and 'undergoes' tables based on the ssn and patient columns, the second JOIN statement joins the 'patient' and 'physician' tables based on the patient's pcp and employeeid columns. The third JOIN statement joins the 'procedure' and 'undergoes' tables based on the code and procedure columns.

The WHERE clause includes the results for only those medical procedures with a cost greater than 5,000.

Practice Online


E R Diagram of Hospital Database:

E R Diagram: SQL Hospital Database.

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous SQL Exercise: Patients who have been prescribed some medication.
Next SQL Exercise: Names of all patients who had at least 2 appointments.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.