SQL Exercise: Find the name and department of the physician
SQL hospital Database: Exercise-8 with Solution
8. From the following tables, write a SQL query to identify the physician and the department with which he or she is affiliated. Return Physician name as "Physician", and department name as "Department".
Sample table: physician
Sample table: department
Sample table: affiliated_with
Sample Solution:
-- This SQL query retrieves the names of physicians and their affiliated departments from the physician, department, and affiliated_with tables.
SELECT p.name AS "Physician", -- Selects the name column from the physician table and aliases it as "Physician"
d.name AS "Department" -- Selects the name column from the department table and aliases it as "Department"
FROM physician p, -- Specifies the physician table with alias 'p'
department d, -- Specifies the department table with alias 'd'
affiliated_with a -- Specifies the affiliated_with table with alias 'a'
WHERE p.employeeid=a.physician -- Joins the physician table with the affiliated_with table on the physician's employee ID
AND a.department=d.departmentid; -- Joins the affiliated_with table with the department table on the department ID
Sample Output:
Physician | Department -------------------+------------------ John Dorian | General Medicine Elliot Reid | General Medicine Christopher Turk | General Medicine Christopher Turk | Surgery Percival Cox | General Medicine Bob Kelso | General Medicine Todd Quinlan | Surgery John Wen | General Medicine John Wen | Surgery Keith Dudemeister | General Medicine Molly Clock | Psychiatry (11 rows)
Explanation:
The said query in SQL that selects the name of physicians and the department they are affiliated with from the physician table, department table, and affiliated_with table.
The query uses a join to combine data from the three tables. It selects the physician name from the physician table, department name from the department table, and uses the affiliated_with table to link the two. The affiliated_with table contains foreign keys to the physician and department tables, which are used to join the tables on their respective IDs.
The column headers will be labeled "Physician" and "Department", respectively.
Pictorial presentation:
Practice Online
E R Diagram of Hospital Database:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous SQL Exercise: Count the number of unavailable rooms.
Next SQL Exercise: Physicians who are trained in a special treatment.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics