w3resource

SQL Exercise: Find nurses who have ever been on call for room 122

SQL hospital Database: Exercise-35 with Solution

35. From the following table, write a SQL query to find out, which nurses have been on call for room 122 in the past. Return name of the nurses.

Sample table: nurse


Sample table: on_call


Sample table: room


Sample Solution:


-- Selecting the name of nurses
SELECT n.name -- Selecting the name column from the nurse table
FROM nurse n -- Specifies the nurse table and aliases it as "n"
WHERE employeeid IN -- Filters the nurses to include only those whose employee ID is present in the subquery
    ( SELECT oc.nurse -- Subquery: Selects the nurse column from the on_call table
     FROM on_call oc, -- Subquery: Specifies the on_call table and aliases it as "oc"
          room r -- Subquery: Specifies the room table and aliases it as "r"
     WHERE oc.blockfloor = r.blockfloor -- Subquery: Joins the on_call table with the room table based on block floor
       AND oc.blockcode = r.blockcode -- Subquery: Adds a condition for the block code in the join
       AND r.roomnumber = 122 ); -- Subquery: Filters the rows to include only those where room number is 122

Sample Output:

      name
-----------------
 Laverne Roberts
 Paul Flowers
(2 rows)	

Explanation:

The said query in SQL that selects the name of the nurse who is on-call for the same block and floor as room number 122.

In the subquery the nurse ID from the 'on_call' table, which stores information about nurses who are on call. A join builds with the 'room' table and 'on_call' table, to match the block and floor of the room number 122 with the corresponding block and floor of the nurse's on-call shift.

The outer query then selects the name of the nurse using the nurse's employee ID, which is found in the 'nurse' table.

The WHERE clause filters the nurse records based on whether their employee ID is in the list of nurse IDs returned by the subquery.

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: Medical procedures done after certification expired.
Next SQL Exercise: Patients who have been prescribed some medication.

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.