Session 3: SQL (B): Parts 3 & 4 Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram. Not for commercial use. Do not redistribute. Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram. Not for commercial use. Do not redistribute.
Using JOINs
3 Types of Joins Equijoin Non-equijoin Outer join Self join
4 What Is an Equijoin? EMP DEPT EMPNO ENAME DEPTNO KING BLAKE CLARK JONES MARTIN ALLEN TURNER JAMES WARD FORD SMITH rows selected. DEPTNO DNAME LOC ACCOUNTING NEW YORK 30 SALES CHICAGO 10 ACCOUNTINGNEW YORK 20 RESEARCHDALLAS 30 SALES CHICAGO 20 RESEARCHDALLAS rows selected. Foreign key Primary key
5 Using Table Aliases Simplify queries by using table aliases. SQL> SELECT emp.empno, emp.ename, emp.deptno, 2 dept.deptno, dept.loc 3 FROM emp, dept 4 WHERE emp.deptno=dept.deptno SQL> SELECT e.empno, e.ename, e.deptno, 2 d.deptno, d.loc 3 FROM emp e, dept d 4 WHERE e.deptno=d.deptno;
6 Joining More Than Two Tables NAMECUSTID JOCKSPORTS 100 TKB SPORT SHOP 101 VOLLYRITE 102 JUST TENNIS 103 K+T SPORTS 105 SHAPE UP 106 WOMENS SPORTS rows selected. NAMECUSTID JOCKSPORTS 100 TKB SPORT SHOP 101 VOLLYRITE 102 JUST TENNIS 103 K+T SPORTS 105 SHAPE UP 106 WOMENS SPORTS rows selected. CUSTOMER CUSTID ORDID rows selected. CUSTID ORDID rows selected.ORD ORDID ITEMID rows selected. ORDID ITEMID rows selected.ITEM
7 Non-Equijoins EMPSALGRADE “salary in the EMP table is between low salary and high salary in the SALGRADE table” EMPNO ENAME SAL KING BLAKE CLARK JONES MARTIN ALLEN TURNER JAMES rows selected. GRADE LOSAL HISAL
8 Retrieving Records with Non-Equijoins ENAME SAL GRADE JAMES SMITH ADAMS rows selected. SQL> SELECT e.ename, e.sal, s.grade 2FROMemp e, salgrade s 3WHERE e.sal 4BETWEEN s.losal AND s.hisal
9 Outer Joins EMP DEPT No employee in the OPERATIONS department ENAMEDEPTNO KING10 BLAKE30 CLARK10 JONES20... DEPTNO DNAME ACCOUNTING 30 SALES 10 ACCOUNTING 20RESEARCH... 40OPERATIONS
10 Outer Joins You use an outer join to also see rows that do not usually meet the join condition Here are two updated examples You use an outer join to also see rows that do not usually meet the join condition Here are two updated examples SELECTtable1.column, table2.column FROMtable1 LEFT JOIN table2 ONtable1.column = table2.column SELECTtable1.column, table2.column FROMtable1 LEFT JOIN table2 ONtable1.column = table2.column SELECTtable1.column, table2.column FROMtable1 RIGHT JOIN table2 ONtable1.column = table2.column SELECTtable1.column, table2.column FROMtable1 RIGHT JOIN table2 ONtable1.column = table2.column
11 Using Outer Joins SQL> SELECTe.ename, d.deptno, d.dname 2 FROMemp e RIGHT JOIN dept d 3 ONe.deptno = d.deptno 4 ORDER BYe.deptno ENAME DEPTNO DNAME KING 10 ACCOUNTING CLARK 10 ACCOUNTING OPERATIONS 15 rows selected.
12 Self Joins EMP (WORKER) EMP (MANAGER) “MGR in the WORKER table is equal to EMPNO in the MANAGER table” EMPNOENAME MGR KING 7698BLAKE CLARK JONES MARTIN ALLEN7698 EMPNOENAME KING 7698BLAKE
13 Joining a Table to Itself WORKER.ENAME WORKS FOR MANAGER.ENAME BLAKE works for KING CLARK works for KING JONES works for KING MARTIN works for BLAKE rows selected. WORKER.ENAME WORKS FOR MANAGER.ENAME BLAKE works for KING CLARK works for KING JONES works for KING MARTIN works for BLAKE rows selected. SQL> SELECT worker.ename +' works for '+ manager.ename 2 FROM emp worker, emp manager 3 WHERE worker.mgr = manager.empno
Group Functions
15 What Are Group Functions? Group functions operate on sets of rows to give one result per group. EMP “maximum salary in salary in the EMP table” DEPTNO SAL MAX(SAL)
16 Types of Group Functions AVG COUNT MAX MIN STDDEV SUM VARIANCE AVG COUNT MAX MIN STDDEV SUM VARIANCE
17 Using AVG and SUM Functions AVG(SAL) MAX(SAL) MIN(SAL) SUM(SAL) You can use AVG and SUM for numeric data. SQL> SELECTAVG(sal), MAX(sal), 2MIN(sal), SUM(sal) 3FROMemp 4WHEREjob LIKE 'SALES%'
18 Using MIN and MAX Functions You can use MIN and MAX for any datatype. SQL> SELECTMIN(hiredate), MAX(hiredate) 2 FROMemp MIN(HIRED MAX(HIRED DEC JAN-83
19 Using the COUNT Function COUNT(*) SQL> SELECTCOUNT(*) 2 FROMemp 3 WHEREdeptno = 30 COUNT(*) returns the number of rows in a table.
20 Using the COUNT Function COUNT(expr) returns the number of nonnull rows. SQL> SELECTCOUNT(comm) 2 FROMemp 3 WHEREdeptno = 30 COUNT(COMM)
21 Group Functions and Null Values Group functions ignore null values in the column. SQL> SELECT AVG(comm) 2 FROM emp AVG(COMM)
22 Using the ISNULL Function with Group Functions The ISNULL function forces group functions to include null values. SQL> SELECT AVG(ISNULL(comm,0)) 2 FROM emp AVG(ISNULL(COMM,0))
23 Creating Groups of Data EMP “average salary in EMP table for each department” DEPTNO SAL DEPTNO AVG(SAL)
24 Using the GROUP BY Clause All columns in the SELECT list that are not in group functions must be in the GROUP BY clause. SQL> SELECT deptno, AVG(sal) 2 FROM emp 3 GROUP BY deptno DEPTNO AVG(SAL)
25 Using the GROUP BY Clause The GROUP BY column does not have to be in the SELECT list. SQL> SELECT AVG(sal) 2 FROM emp 3 GROUP BY deptno AVG(SAL)
26 Grouping by More Than One Column EMP “sum salaries in the EMP table for each job, grouped by department” DEPTNO JOB SAL MANAGER PRESIDENT CLERK CLERK CLERK ANALYST MANAGER SALESMAN MANAGER SALESMAN CLERK SALESMAN SALESMAN 1250 JOB SUM(SAL) CLERK 1300 MANAGER 2450 PRESIDENT 5000 ANALYST 6000 CLERK 1900 MANAGER 2975 CLERK 950 MANAGER 2850 SALESMAN 5600 DEPTNO
27 Using the GROUP BY Clause on Multiple Columns SQL> SELECT deptno, job, sum(sal) 2 FROM emp 3 GROUP BY deptno, job DEPTNO JOB SUM(SAL) CLERK MANAGER PRESIDENT ANALYST CLERK rows selected.
28 Illegal Queries Using Group Functions Any column or expression in the SELECT list that is not an aggregate function must be in the GROUP BY clause. SQL> SELECTdeptno, COUNT(ename) 2 FROMemp SQL> SELECTdeptno, COUNT(ename) 2 FROMemp SELECT deptno, COUNT(ename) * ERROR at line 1: not a single-group group function SELECT deptno, COUNT(ename) * ERROR at line 1: not a single-group group function Column missing in the GROUP BY clause
29 Illegal Queries Using Group Functions You cannot use the WHERE clause to restrict groups. You use the HAVING clause to restrict groups. You cannot use the WHERE clause to restrict groups. You use the HAVING clause to restrict groups. SQL> SELECT deptno, AVG(sal) 2 FROM emp 3 WHERE AVG(sal) > GROUP BY deptno SQL> SELECT deptno, AVG(sal) 2 FROM emp 3 WHERE AVG(sal) > GROUP BY deptno WHERE AVG(sal) > 2000 * ERROR at line 3: group function is not allowed here WHERE AVG(sal) > 2000 * ERROR at line 3: group function is not allowed here Cannot use the WHERE clause to restrict groups to restrict groups Cannot use the WHERE clause to restrict groups to restrict groups
30 Excluding Group Results “maximum salary per department greater than $2900” EMP DEPTNO SAL DEPTNO MAX(SAL)
31 Using the HAVING Clause SQL> SELECT deptno, max(sal) 2 FROM emp 3 GROUP BY deptno 4 HAVING max(sal)>2900 DEPTNO MAX(SAL)
32 Using the HAVING Clause SQL> SELECT job, SUM(sal) PAYROLL 2 FROM emp 3 WHERE job NOT LIKE 'SALES%' 4 GROUP BY job 5 HAVING SUM(sal)> ORDER BY SUM(sal) JOB PAYROLL ANALYST 6000 MANAGER 8275
Sub-queries
34 What Is a Subquery? A subquery is a SELECT statement embedded in a clause of another SQL statement. SELECT... FROM... WHERE... (SELECT... FROM... WHERE...) MainQuery Subquery
35 Subqueries The subquery (inner query) executes once before the main query. The result of the subquery is used by the main query (outer query). The subquery (inner query) executes once before the main query. The result of the subquery is used by the main query (outer query). SELECTselect_list FROMtable WHEREexpr operator (SELECTselect_list FROMtable)
SQL> SELECT ename 2 FROM emp 3 WHERE sal > 4 (SELECT sal 5 FROM emp 6 WHERE empno = 7566) Using a Subquery ENAME KING FORD SCOTT ENAME KING FORD SCOTT
37 Correlated Subqueries Used to affect row-by-row processing, each subquery is executed once for every row of the outer query. GET candidate row EXECUTE inner query using candidate row value USE value(s) from inner query to qualify candidate row
38 Correlated Subqueries SELECT outer1, outer2,... FROM table1 alias1 WHERE outer1 operator (SELECT inner1 FROM table2 alias2 WHERE alias1.outer2 = alias2.inner1) subquery references a column from a table in the parent query. The subquery references a column from a table in the parent query.
39 Using Correlated Subqueries Each time the outer query is processed the inner query is evaluated. SQL> SELECT empno, sal, deptno 2 FROM emp outr 3 WHERE sal > (SELECT AVG(sal) 4 FROM emp innr 5 WHERE outr.deptno = innr.deptno) EMPNO SAL DEPTNO rows selected. EMPNO SAL DEPTNO rows selected. Find all employees who make more than the average salary in their department.
40 Using the EXISTS Operator If a subquery row value is found: – The search does not continue in the inner query. – The condition is flagged TRUE. If a subquery row value is not found: – The condition is flagged FALSE. – The search continues in the inner query. If a subquery row value is found: – The search does not continue in the inner query. – The condition is flagged TRUE. If a subquery row value is not found: – The condition is flagged FALSE. – The search continues in the inner query.
41 Find employees who have at least one person reporting to them. Using the EXISTS Operator EMPNO ENAME JOB DEPTNO KING PRESIDENT BLAKE MANAGER CLARK MANAGER JONES MANAGER rows selected. SQL> SELECT empno, ename, job, deptno 2 FROM emp outr 3 WHERE EXISTS (SELECT empno 4 FROM emp innr 5 WHERE innr.mgr = outr.empno)
42 Find all departments that do not have any employees. Using the NOT EXISTS Operator DEPTNO DNAME OPERATIONS DEPTNO DNAME OPERATIONS SQL> SELECTdeptno, dname 2 FROM dept d 3 WHERENOT EXISTS (SELECT * 4 FROM emp e 5 WHERE d.deptno = e.deptno)
Views
44 What Is a View? EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO KING PRESIDENT 17-NOV BLAKE MANAGER MAY CLARK MANAGER JUN JONES MANAGER APR MARTIN SALESMAN SEP ALLEN SALESMAN FEB TURNER SALESMAN SEP JAMES CLERK DEC WARD SALESMAN FEB FORD ANALYST DEC SMITH CLERK DEC SCOTT ANALYST DEC ADAMS CLERK JAN MILLER CLERK JAN EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO KING PRESIDENT 17-NOV BLAKE MANAGER MAY CLARK MANAGER JUN JONES MANAGER APR MARTIN SALESMAN SEP ALLEN SALESMAN FEB TURNER SALESMAN SEP JAMES CLERK DEC WARD SALESMAN FEB FORD ANALYST DEC SMITH CLERK DEC SCOTT ANALYST DEC ADAMS CLERK JAN MILLER CLERK JAN EMP Table EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO KING PRESIDENT 17-NOV CLARK MANAGER JUN MILLER CLERK JAN JONES MANAGER APR SCOTT ANALYST DEC ADAMS CLERK JAN SMITH CLERK DEC FORD ANALYST DEC BLAKE MANAGER MAY MARTIN SALESMAN SEP ALLEN SALESMAN FEB TURNER SALESMAN SEP JAMES CLERK DEC WARD SALESMAN FEB EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO KING PRESIDENT 17-NOV CLARK MANAGER JUN MILLER CLERK JAN JONES MANAGER APR SCOTT ANALYST DEC ADAMS CLERK JAN SMITH CLERK DEC FORD ANALYST DEC BLAKE MANAGER MAY MARTIN SALESMAN SEP ALLEN SALESMAN FEB TURNER SALESMAN SEP JAMES CLERK DEC WARD SALESMAN FEB EMPNO ENAME JOB KING PRESIDENT 7782 CLARK MANAGER 7934 MILLER CLERK EMPVU10 View EMPVU10 View
45 Creating a View Create a view, EMPVU10, that contains details of employees in department 10. SQL> CREATE VIEW empvu10 2 AS SELECTempno, ename, job 3 FROMemp 4 WHEREdeptno = 10 View created.
46 Retrieving Data from a View EMPLOYEE_NUMBER NAME SALARY BLAKE MARTIN ALLEN TURNER JAMES WARD rows selected. EMPLOYEE_NUMBER NAME SALARY BLAKE MARTIN ALLEN TURNER JAMES WARD rows selected. SQL> SELECT * 2 FROMsalvu30
47 Creating a Complex View Create a complex view that contains group functions to display values from two tables. SQL> CREATE VIEWdept_sum_vu 2 (name, minsal, maxsal, avgsal) 3 AS SELECTd.dname, MIN(e.sal), MAX(e.sal), 4AVG(e.sal) 5 FROMemp e, dept d 6 WHEREe.deptno = d.deptno 7 GROUP BY d.dname View created.
48 Removing a View Remove a view without losing data because a view is based on underlying tables in the database. SQL> DROP VIEW empvu10 View dropped. DROP VIEW view
49 Summary A view is derived from data in other tables or other views. A view provides the following advantages: – Restricts database access – Simplifies queries – Provides data independence – Allows multiple views of the same data – Can be dropped without removing the underlying data A view is derived from data in other tables or other views. A view provides the following advantages: – Restricts database access – Simplifies queries – Provides data independence – Allows multiple views of the same data – Can be dropped without removing the underlying data