w3resource

SQL Exercise: Physicians, a medical procedure without certification

SQL hospital Database: Exercise-31 with Solution

31. From the following tables, write a SQL query to find all physicians who have performed a medical procedure but are not certified to do so. Return Physician name as "Physician".

Sample table: physician


Sample table: undergoes


Sample table: trained_in


Sample Solution:


-- This SQL query retrieves the names of physicians who are not trained in any procedure, based on their absence in the trained_in table.

SELECT name AS "Physician" -- Selects the name column from the physician table and aliases it as "Physician"
FROM physician -- Specifies the physician table
WHERE employeeid IN -- Filters the physicians to include only those whose employee ID is present in the subquery
    ( SELECT undergoes.physician -- Subquery: Selects the physician column from the undergoes table
     FROM undergoes -- Subquery: Specifies the undergoes table
     LEFT JOIN trained_In ON undergoes.physician=trained_in.physician -- Subquery: Left joins the undergoes table with the trained_in table on the physician's employee ID
     AND undergoes.procedure=trained_in.treatment -- Subquery: Adds a condition for the procedure in the join
     WHERE treatment IS NULL ); -- Subquery: Filters the rows to include only those where treatment is NULL (indicating the physician is not trained in any procedure)

Sample Output:

    Physician
------------------
 Christopher Turk
(1 row)

Explanation:

The said query in SQL retrieves the name of physicians who have not been trained in a particular medical procedure by looking for records in the 'undergoes' table where a corresponding record in the 'trained_in' table with the same physician and procedure does not exist.

From the outer query filters the results by selecting only those records where the "employeeid" column is found in a subquery.

In the subquery the LEFT JOIN keyword joins the 'undergoes' and 'trained_in' tables based on the common columns physician, procedure, and treatment.

The WHERE clause in the subquery filters the results of the join to include only those records where "treatment" is NULL.

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: Make a report of specified queries.
Next SQL Exercise: Doctors do the same procedure but are not certified.

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.