1 JOIN SUBQUERY Structured Query Language (SQL) - Part III.

28
1 JOIN SUBQUERY Structured Query Language (SQL) - Part III

Transcript of 1 JOIN SUBQUERY Structured Query Language (SQL) - Part III.

Page 1: 1 JOIN SUBQUERY Structured Query Language (SQL) - Part III.

1

JOINSUBQUERY

JOINSUBQUERY

Structured Query Language (SQL) - Part III

Page 2: 1 JOIN SUBQUERY Structured Query Language (SQL) - Part III.

2

JOINJOIN

JOIN allows us to retrieve related data from more than one table

SELECT statement is used for joining tables Attributes to be selected are listed following the keyword

SELECT Tables participating in the join operation are listed in the

FROM clause The join condition is specified in the WHERE clause

You may use any comparison operator (=, >, <, <=, >=. !=, <>, !>, !<) here, though equality is more commonly used

Page 3: 1 JOIN SUBQUERY Structured Query Language (SQL) - Part III.

3

JOINING MORE THAN TWO TABLESJOINING MORE THAN TWO TABLES

EMPLOYEEEID Ename Dcode Rank Salary1001 John 1 1 300001002 Joe 2 2 400001003 Jack 3 2 400001004 Jane 2 1 300001005 Jill 2 3 450001006 Jeb 3 1 350001007 Jim 1 1 30000

DEPARTMENTDcode Dname1 Accounting2 Finance3 Sales

RANKSRank Title Min Sal Max Sal1 Supervisor 30000 400002 Jr. Mgr. 35000 450003 Manager 40000 600004 Asst. Director 50000 800005 Director 70000 100000

Page 4: 1 JOIN SUBQUERY Structured Query Language (SQL) - Part III.

4

JOINJOIN

/* List employee ids and names with their department names */

SELECT eid, ename, dnameFROM Employee, DepartmentWHERE Employee.dcode = Department.dcode;

EID Ename Dname1001 John Accounting 1002 Joe Finance1003 Jack Sales1004 Jane Finance1005 Jill Finance1006 Jeb Sales1007 Jim Accounting

Page 5: 1 JOIN SUBQUERY Structured Query Language (SQL) - Part III.

5

JOINJOIN

Qualifying column names in a query when column names are not unique, they must be qualified by

the table names to eliminate ambiguity when column names are unique, qualifying is not required but

may be done for documentation purpose Example:

SELECT eid, ename, dnameFROM Employee, DepartmentWHERE Employee.dcode = Department.dcode;

/* This statement qualifies each column name by the appropriate table name.Note that here qualification is required only in the WHERE clause */SELECT Employee.eid, Employee.ename, Department.dnameFROM Employee, DepartmentWHERE Employee.dcode = Department.dcode;

Page 6: 1 JOIN SUBQUERY Structured Query Language (SQL) - Part III.

6

JOINJOIN

Using aliases an alias assigns a unique identifier to the table in a query the alias must follow the table name use a space to separate the table name from its alias Example:

SELECT Employee.eid, Employee.ename, Department.dnameFROM Employee, DepartmentWHERE Employee.dcode = Department.dcode;

/* This statement uses table name aliases. */SELECT e.eid, e.ename, d.dnameFROM Employee e, Department dWHERE e.dcode = d.dcode;

Page 7: 1 JOIN SUBQUERY Structured Query Language (SQL) - Part III.

7

JOINJOIN

/* List the employees and their department namesfor those that earn more than 35000 */

SELECT e.eid, e.ename, e.salary, d.dnameFROM Employee e, Department dWHERE e.salary > 35000 AND e.dcode = d.dcode; EID Ename Salary Dname

1002 Joe 40000 Finance1003 Jack 40000 Sales1005 Jill 45000 Finance

You may use additional selection criteria with join Example:

Page 8: 1 JOIN SUBQUERY Structured Query Language (SQL) - Part III.

8

JOINING MORE THAN TWO TABLESJOINING MORE THAN TWO TABLES

SELECT e.eid, e.ename, d.dname, r.titleFROM Employee e, Department d, Ranks rWHERE e.dcode = d.dcode

AND e.rank = r.rankORDER By d.dname, e.rank desc;

EID Ename Dname Title1001 John Accounting Supervisor1007 Jim Accounting Supervisor1005 Jill Finance Manager1002 Joe Finance Jr. Mgr1004 Jane Finance Supervisor1003 Jack Sales Jr. Mgr1006 Jeb Sales Supervisor

Page 9: 1 JOIN SUBQUERY Structured Query Language (SQL) - Part III.

9

JOINING A TABLE TO ITSELFJOINING A TABLE TO ITSELF

EMPEID Ename MgrID1001 John 10021002 Joe Null1003 Jack 10041004 Jane Null1005 Jill 10041006 Jeb 10041007 Jim 1002

/* List the manager name for each employee Notice the use of column headings in the query */

SELECT e1.ename “Employee” , e2.ename “Manager”FROM Emp e1, Emp e2WHERE e1.mgrid = e2.eid

Employee ManagerJohn JoeJack JaneJill JaneJeb JaneJim Joe

Page 10: 1 JOIN SUBQUERY Structured Query Language (SQL) - Part III.

10

OUTER JOINOUTER JOIN

Outer join is indicated by a + sign in Oracle Oracle supports left and right outer joins only Left (right) outer join retains the unmatched rows from the

left (right) table in the result /* This is an example of right outer join */

SELECT e.eid, e.ename, r.rank, r.titleFROM Employee e, Ranks rWHERE e.rank(+) = r.rank;

EID Ename Rank Title1001 John 1 Supervisor1002 Joe 2 Jr. Mgr.1003 Jack 2 Jr. Mgr.1004 Jane 1 Supervisor1005 Jill 3 Manager1006 Jeb 1 Supervisor1007 Jim 1 SupervisorNull Null 4 Asst. DirectorNull Null 5 Director

Page 11: 1 JOIN SUBQUERY Structured Query Language (SQL) - Part III.

11

JOINS with NULL ValuesJOINS with NULL Values

Null does not have a value. So it does not match with any value, including another null value.

Example:

TABLE1A B1 OneNULL Three4 Join4

TABLE2C DNULL Two4 Four

SELECT A, B, DFROM TABLE1, TABLE2WHERE a = c;

A B D4 Join4 Four

Page 12: 1 JOIN SUBQUERY Structured Query Language (SQL) - Part III.

12

JOINS with NULL ValuesJOINS with NULL Values

You can use outer join to detect null values in a column. Example:

/* Left outer join includes all the rows from the left table in the result */SELECT *FROM TABLE1, TABLE2WHERE a = c (+);

A B C D1 One NULL NULLNULL Three NULL NULL4 Join4 4 Four

TABLE1A B1 OneNULL Three4 Join4

TABLE2C DNULL Two4 Four

Page 13: 1 JOIN SUBQUERY Structured Query Language (SQL) - Part III.

13

SUBQUERIESSUBQUERIES

A subquery is a SELECT statement that is nested inside another SELECT statement or another subquery

There is no restriction on the depth of such nesting A query containing subqueries is evaluated starting with the

innermost subquery Example:

Suppose we want to list employees that earn the lowest salary This requires two queries, based on what we have learnt so far

First we will find the minimum salary earned by an employee Then we will use the min salary value to list the names of employees who

earn this salary

We can combine these two steps in to a single query by nesting a subquery within a query

Page 14: 1 JOIN SUBQUERY Structured Query Language (SQL) - Part III.

14

SUBQUERIESSUBQUERIES

All examples in this section are based on the tables in Bordoloi (pp. 82, 83).

/* Find the minimum salary */SELECT min(salary)FROM Employee;

Min(Salary) 25000

/* List names of employees that earn the min salary found in the previous step */SELECT fname, lnameFROM EmployeeWHERE salary = 25000;

/* Use of subquery */SELECT fname, lnameFROM EmployeeWHERE salary =

(SELECT min(salary) FROM Employee);

Fname LnameAlicia ZelayaJoyce EnglishAhmad Jabbar

Fname LnameAlicia ZelayaJoyce EnglishAhmad Jabbar

Page 15: 1 JOIN SUBQUERY Structured Query Language (SQL) - Part III.

15

SUBQUERIESSUBQUERIES

Three basic types of subqueries One that returns a single value (Example in previous slide)

normally uses aggregate functions The returned value is compared in the outer query using a comparison

operator such as =, !=, >, <, etc.

One that returns a list of values these values are from a single column, such as a list of order numbers,

list of majors, list of departments, etc. Outer query uses a list comparison operator, such as IN, or an

comparison operator modified by ANY or ALL clause. SELECT clause of the subquery must contain a single column name

subqueries that are used to check for existence of data Outer query uses the EXISTS keyword.

Page 16: 1 JOIN SUBQUERY Structured Query Language (SQL) - Part III.

16

SUBQUERY SYNTAXSUBQUERY SYNTAX

A subquery uses a SELECT statement It is enclosed within parentheses It may appear in the WHERE clause or the HAVING clause

in the outer query A subquery cannot use the ORDER BY clause The result of a subquery must be join compatible with

WHERE / HAVING clause of the outer query, i.e., the result must be comparable.

Page 17: 1 JOIN SUBQUERY Structured Query Language (SQL) - Part III.

17

SUBQUERIES WITH INSUBQUERIES WITH IN

WHERE <expression> [NOT] IN (subquery) Subquery returns a list Example:

/* List employees that have a male dependent */SELECT lname, fnameFROM EmployeeWHERE ssn IN ( SELECT essn

FROM Dependentwhere sex = ‘M’);

Lname FnameSmith JohnWong Franklin

Wallace Jennifer

Page 18: 1 JOIN SUBQUERY Structured Query Language (SQL) - Part III.

18

SUBQUERIES WITH INSUBQUERIES WITH IN

How is the previous query evaluated?

/* First the subquery is evaluated */SELECT essn FROM Dependentwhere sex = ‘M’;

Essn333445555987654321123456789

/* Then the outer query is evaluated using the result of the subquery */SELECT lname, fnameFROM EmployeeWHERE ssn IN (333445555, 987654321, 123456789);

Page 19: 1 JOIN SUBQUERY Structured Query Language (SQL) - Part III.

19

SUBQUERIES WITH INSUBQUERIES WITH IN

You can get the same result by writing a JOIN query It is, however, desirable to use a subquery in this case because

the result is from a single table

/* The equivalent JOIN query */SELECT lname, fnameFROM Employee, DependentWHERE employee.ssn = dependent.essnAND dependent.sex = ‘M’;

/* Check out the subquery and the join query with sex = ‘F’ *//* Are the results the same? Explain. */

Page 20: 1 JOIN SUBQUERY Structured Query Language (SQL) - Part III.

20

MULTIPLE LEVELS OF NESTINGMULTIPLE LEVELS OF NESTING

Oracle places no limit on the level of nesting

/* List the names of all employees who worked more than 10 hours on the Newbenefits project. */SELECT lname, fnameFROM EmployeeWHERE ssn IN

(SELECT essn FROM Works_onWHERE hours > 10AND pno IN

(SELECT pnumberFROM ProjectWHERE pname = ‘Newbenefits’) );

Page 21: 1 JOIN SUBQUERY Structured Query Language (SQL) - Part III.

21

MULTIPLE LEVELS OF NESTINGMULTIPLE LEVELS OF NESTING

How is the previous query evaluated?/* We start with the innermost subquery */SELECT pnumberFROM ProjectWHERE pname = "Newbenefits”;

Pnumber 30

/* The result is plugged into the next subquery */SELECT essn FROM Works_onWHERE hours > 10AND pno IN (30);

Essn999887777987654321

/* Then the final query is evaluated */SELECT lname, fnameFROM EmployeeWHERE ssn IN (999887777, 987654321);

Page 22: 1 JOIN SUBQUERY Structured Query Language (SQL) - Part III.

22

USE OF ANY or ALLUSE OF ANY or ALL

WHERE <expression> <comparison operator> [ANY | ALL] (subquery)

The result of the subquery in this case is a list

/* List all employees that earn more than all ofthe employees in Dept. 5 */SELECT lname, fnameFROM EmployeeWHERE salary > ALL

(SELECT salary FROM Employee WHERE dno = 5);

/* Can you reformulate the subquery so that ALL is not required in the outer query? What will be the result if we replace > ALL by = ALL? */

Lname FnameWallace JenniferBorg James

Page 23: 1 JOIN SUBQUERY Structured Query Language (SQL) - Part III.

23

USE OF ANY or ALLUSE OF ANY or ALL

= ANY is same as IN

/* List the employees that have a female dependent Following two queries are equivalent */SELECT lname, fnameFROM EmployeeWHERE ssn = ANY

(SELECT essn FROM Dependent WHERE sex = ‘F’);

Lname FnameSmith JohnWong Franklin

SELECT lname, fnameFROM EmployeeWHERE ssn IN

(SELECT essn FROM Dependent WHERE sex = ‘F’);

Page 24: 1 JOIN SUBQUERY Structured Query Language (SQL) - Part III.

24

USE OF ANY or ALLUSE OF ANY or ALL

!= ANY is not the same as NOT IN NOT IN (1,2,3) means != 1and != 2 and != 3 != ANY (1,2,3) means != 1 or !=2 or != 3

!= ALL is same as NOT IN/* List all employees that don’t have a dependent */

SELECT lname, fnameFROM EmployeeWHERE ssn != ALL

(SELECT essn FROM Dependent);

/* You will get the same result by replacing != ALL by NOT INWhat will be the result if you simply replace ALL by ANY in the above query? */

Lname FnameZelaya AliciaNarayan RameshEnglish JoyceJabbar AhmadBorg James

Page 25: 1 JOIN SUBQUERY Structured Query Language (SQL) - Part III.

25

CORRELATED SUBQUERIESCORRELATED SUBQUERIES

In correlated subqueries, the inner query depends on values provided by the outer query

The inner query is executed once for each row that might be selected by the outer query

/* List all employees who have worked 10 hours on any project */SELECT lname, fnameFROM EmployeeWHERE 10 IN

(SELECT hours FROM Works_on WHERE ssn = essn);

/* What is the equivalent join query for the above?

Lname FnameWong FranklinZelaya Alicia

Page 26: 1 JOIN SUBQUERY Structured Query Language (SQL) - Part III.

26

USE of EXISTSUSE of EXISTS

WHERE [NOT] EXISTS (subquery) Checks for existence of data - returns TRUE or FALSE A subquery introduced with EXISTS is always a corelated

subquery The SELECT list in the subquery is invariably *, because

there is no need for selecting a column

/* List all employees that have one or more dependents */SELECT lname, fnameFROM EmployeeWHERE EXISTS

(SELECT * FROM Dependent WHERE ssn = essn);

/* How many times does the subquery execute in the above query? */

Lname FnameSmith JohnWong FranklinWallace Jennifer

Page 27: 1 JOIN SUBQUERY Structured Query Language (SQL) - Part III.

27

USE of EXISTSUSE of EXISTS

/* List all employees that do not have any dependent */

SELECT lname, fnameFROM EmployeeWHERE NOT EXISTS

(SELECT * FROM Dependent WHERE ssn = essn);

Lname FnameZelaya AliciaNarayan RameshEnglish JoyceJabbar AhmadBorg James

Page 28: 1 JOIN SUBQUERY Structured Query Language (SQL) - Part III.

28

SELF TESTSELF TEST

List student name, major and department name for all students

List student name, major, and department name for students that have a GPA > 3.0