Docsity

SQL Joins and Set Operations: A Comprehensive Guide, Lecture notes of Data Mining

Partial preview of the text

Download SQL Joins and Set Operations: A Comprehensive Guide and more Lecture notes Data Mining in PDF only on Docsity!

CS348 INFORMATION SYSTEMS

Hisham Benotman

Most slides are adopted with permission from A. Alawini, D. Maier, L. Delacambre, S. Davidson, and A. Parameswaran 1

Outline

  • Joins
  • Set operations 2

Example Database

Cross Product

SELECT *

FROM Department, Employee

JOIN (INNER JOIN)

SELECT *

FROM Employee emp JOIN Department dept

ON emp.DepartmentID = dept.DepartmentID

Natural Join

SELECT *

FROM Employee emp NATURAL JOIN Department dept

Natural Join Problems?

SELECT *

FROM Employee emp NATURAL JOIN Department dept

11 OUTER JOINS

  • Sometimes need special variations of joins:
    • I want to see all employees and their departments
    • … But what if there’s a department with no employees?
    • Or what if an employee has not been assigned to a department?
  • Outer join:
    • Most common is left outer join

Left Outer Join

SELECT *

FROM Employee emp LEFT OUTER JOIN Department dept

ON emp.DepartmentID = dept.DepartmentID

Right Outer Join

SELECT *

FROM Employee emp RIGHT OUTER JOIN Department dept

ON emp.DepartmentID = dept.DepartmentID

Notes

✓Note about joining multiple tables

16

SELECT *

FROM Employee emp, Department dept WHERE emp.DepartmentID = dept.DepartmentID

LastName Departme ntID Department Name Departmen tID DepID EmpLastName DepName Jones 33 Engineering 33 1 Jones Sara Jones 33 Engineering 33 2 Jones Tom Smith 34 Clerical 34 3 Smith Jennifer Smith 34 Clerical 34 4 Smith Jessica

SELECT *

FROM Employee emp, Department dept, Dependents D WHERE emp.DepartmentID = dept.DepartmentID AND emp.LastName = D.EmpLastName

LastName Departme ntID Department Name Departmen tID DepID EmpLastName DepName Jones 33 Engineering 33 1 Jones Sara Jones 33 Engineering 33 2 Jones Tom Smith 34 Clerical 34 3 Smith Jennifer Smith 34 Clerical 34 4 Smith Jessica DepHospitalVisits DepID VisitDate Cost 1 1/2/2019 500 1 12/5/2019 2600 1 5/5/2020 900 2 4/4/2020 150 2 4/9/2020 13000 3 3/12/2020 1200 3 3/29/2020 2300 Join using DepID. How many rows in the result?