Single-Row Functions. SQL Functions FunctionInput arg 1 arg 2 arg n Function performs action OutputResultvalue.

Slides:



Advertisements
Similar presentations
Displaying Data from Multiple Tables. Objectives After completing this lesson, you should Be able to do the following: Write SELECT statements to accessWrite.
Advertisements

Copyright  Oracle Corporation, All rights reserved. 3 Displaying Data from Multiple Tables.
Displaying Data from Multiple Tables. Objectives After completing this lesson, you should be able to do the following: Write SELECT statements to access.
Chapter 4 JOINING TABLES & FUNCTION Lecture by Ty Rasmey
Copyright  Oracle Corporation, All rights reserved. 4 Aggregating Data Using Group Functions.
Subqueries 11. Objectives After completing this lesson, you should be able to do the following: Describe the types of problems that subqueries can solve.
1Eyad Alshareef Enhanced Guide to Oracle 10g Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data.
Copyright  Oracle Corporation, All rights reserved. 2 Restricting and Sorting Data.
Copyright  Oracle Corporation, All rights reserved. 6 Subqueries.
5 5 Aggregating Data Using Group Functions Important Legal Notice:  Materials on this lecture are from a book titled “Oracle Education” by Kochhar, Gravina,
Aggregating Data Using Group Functions. Objectives After completing this lesson, you should be able to do the following: Identify the available group.
Copyright  Oracle Corporation, All rights reserved. 5 Aggregating Data Using Group Functions.
1Eyad alshareef Enhanced Guide to Oracle 10g Chapter 3: Using SQL Queries to Insert, Update, Delete, and View Data.
GROUP FUNCTIONS. Objectives After completing this lesson, you should be able to do the following: Identify the available group functions Describe the.
Aggregating Data Using Group Functions. Objectives After completing this lesson, you should be able to do the following: Identify the available group.
6 6 Subqueries Important Legal Notice:  Materials on this lecture are from a book titled “Oracle Education” by Kochhar, Gravina, and Nathan (1999), published.
Multiple-Column Subqueries 12. Objectives After completing this lesson, you should be able to do the following: Write a multiple-column subquery Describe.
6-1 Copyright  Oracle Corporation, All rights reserved. Types of Subqueries Single-row subquery Main query Subquery returns CLERK Multiple-row subquery.
Multiple-Column Subqueries. Objectives After completing this lesson, you should be able to do the following: Write a Multiple-column subquery Describe.
Copyright س Oracle Corporation, All rights reserved. 7 Multiple-Column Subqueries.
Copyright  Oracle Corporation, All rights reserved. 7 Multiple-Column Subqueries.
Session 3: SQL (B): Parts 3 & 4 Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram.
4-1 Copyright  Oracle Corporation, All rights reserved. Displaying Data from Multiple Tables.
Functions Oracle Labs 5 & 6. 2/3/2005Adapted from Introduction to Oracle: SQL and PL/SQL 2 SQL Functions Function arg n arg 2 arg 1. Input Resulting Value.
Displaying Data from Multiple Tables (Join) Displaying Data from Multiple Tables (Join) Displaying Data from Multiple Tables (Join Displaying Data from.
Displaying Data from Multiple Tables (Join). EMPNO DEPTNO LOC NEW YORK CHICAGO NEW YORK DALLAS.
Subqueries.
Subqueries.
Copyright س Oracle Corporation, All rights reserved. 5 Aggregating Data Using Group Functions.
Joins & Sub-queries. Oracle recognizes that you may want data that resides in multiple tables drawn together in some meaningful way. One of the most important.
5 Copyright © Oracle Corporation, All rights reserved. Aggregating Data Using Group Functions.
Copyright  Oracle Corporation, All rights reserved. 2 Restricting and Sorting Data.
7 Multiple-Column Subqueries. 7-2 Objectives At the end of this lesson, you should be able to: Write a multiple-column subquery Describe and explain the.
SQL- DQL (Oracle Version). 2 SELECT Statement Syntax SELECT [DISTINCT] column_list FROM table_list [WHERE conditional expression] [GROUP BY column_list]
SQL. Relating Multiple Tables Relational Database Terminology Row PK Column FK Field NULL.
Session 2: SQL (A): Parts 1 and 2 Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram.
4 Displaying Data from Multiple Tables Important Legal Notice:  Materials on this lecture are from a book titled “Oracle Education” by Kochhar, Gravina,
Copyright س Oracle Corporation, All rights reserved. 4 Displaying Data from Multiple Tables.
I-1 Copyright س Oracle Corporation, All rights reserved. Data Retrieval.
SQL: Part 2 Original materials supplied by the Oracle Academic Initiative (OAI). Edited for classroom use by Professor Laku Chidambaram. Not for commercial.
Multiple Table Queries (Inner Joins, Equijoins) Week 3.
Review SQL Advanced. Capabilities of SQL SELECT Statements Selection Projection Table 1 Table 2 Table 1 Join.
Copyright س Oracle Corporation, All rights reserved. I Introduction.
2-1 Limiting Rows Using a Selection “…retrieve all employees in department 10” EMP EMPNO ENAME JOB... DEPTNO 7839KINGPRESIDENT BLAKEMANAGER CLARKMANAGER.
6 Subqueries. 6-2 Objectives At the end of this lesson, you should be able to: Describe the types of problems that subqueries can solve Define subqueries.
Aggregating Data Using Group Functions. Objectives After completing this lesson, you should be able to do the following: –Identify the available group.
Copyright  Oracle Corporation, All rights reserved. 4 Displaying Data from Multiple Tables.
Copyright  Oracle Corporation, All rights reserved. 2 Restricting and Sorting Data.
Displaying Data from Multiple Tables (Join) Displaying Data from Multiple Tables (Join) Displaying Data from Multiple Tables (Join Displaying Data from.
Defining a Column Alias
Copyright  Oracle Corporation, All rights reserved. 4 Displaying Data from Multiple Tables.
Displaying Data from Multiple Tables. Objectives After completing this lesson, you should be able to do the following: –Write SELECT statements to access.
4 Displaying Data from Multiple Tables. 4-2 Objectives At the end of this lesson, you should be able to: Write SELECT statements to access data from more.
Communicating with a RDBMS Using SQL Database SQL> SELECT loc 2 FROM dept; SQL> SELECT loc 2 FROM dept; SQL statement is entered Statement is sent to database.
Displaying Data from Multiple Tables
Displaying Data from Multiple Tables
Aggregating Data Using Group Functions
Subqueries.
Subqueries Schedule: Timing Topic 25 minutes Lecture
Aggregating Data Using Group Functions
(SQL) Aggregating Data Using Group Functions
Aggregating Data Using Group Functions
Aggregating Data Using Group Functions
(SQL) Displaying Data from Multiple Tables
Subqueries Schedule: Timing Topic 25 minutes Lecture
Review SQL Advanced.
Displaying Data from Multiple Tables
Subqueries Schedule: Timing Topic 25 minutes Lecture
Presentation transcript:

Single-Row Functions

SQL Functions FunctionInput arg 1 arg 2 arg n Function performs action OutputResultvalue

Two Types of SQL Functions Functions Single-rowfunctions Multiple-rowfunctions

Single-Row Functions – Manipulate data items – Accept arguments and return one value – May modify the data type – Can be nested – Manipulate data items – Accept arguments and return one value – May modify the data type – Can be nested function_name (column|expression, [arg1, arg2,...])

Single-Row Functions Conversion CharacterNumber Date Single-rowfunctions

Character Functions Characterfunctions LOWERUPPERSUBSTRINGLENLTRIMRTRIMLEFTRIGHT Case conversion functions Character manipulation functions

FunctionResult Case Conversion Functions Convert case for character strings LOWER( ' SQL Course ' ) UPPER( ' SQL Course ' ) sql course SQL COURSE

Using Case Conversion Functions Display the employee number, name, and department number for employee Blake. SELECTempno, ename, deptno FROMemp WHEREename = 'blake' no rows selected no rows selected SELECTempno, ename, deptno FROMemp WHEREename = 'blake' no rows selected no rows selected EMPNO ENAME DEPTNO BLAKE 30 EMPNO ENAME DEPTNO BLAKE 30 SELECTempno, ename, deptno FROMemp WHERE LOWER(ename) = 'blake'

SUBSTRING( ' String ',1,3) LEN(‘String’) LTRIM(‘ String ’) RTRIM(‘ String ’) LEFT(‘String’, 3) RIGHT(‘String’, 3) Str 6 String Str ing FunctionResult Character Manipulation Functions Manipulate character strings

Using the Character Manipulation Functions SELECT SUBSTRING('String',1,3) substr, LEN('String') Lenstr, RTRIM(' string ') Rtrimstr, LTRIM(' string ') Ltrimstr, LEFT('String',3) Leftstr, RIGHT('String',3) Rightstr

Using the ROUND Function SELECT ROUND(45.923,2), ROUND(45.923,0), ROUND(45.923,-1) ROUND(45.923,2) ROUND(45.923,0) ROUND(45.923,-1)

SELECT FLOOR(123.45), FLOOR( ), FLOOR(123.95) Using the FLOOR,CEILING Functions SELECT CEILING(123.45), CEILING( ), CEILING(0.0)

Aggregating Data Using Group Functions

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)

Types of Group Functions – AVG – COUNT – MAX – MIN – SUM – AVG – COUNT – MAX – MIN – SUM

Using Group Functions SELECT[column,] group_function(column) FROMtable [WHEREcondition] [GROUP BYcolumn] [ORDER BYcolumn]

Using AVG and SUM Functions AVG(SAL) MAX(SAL) MIN(SAL) SUM(SAL) You can use AVG and SUM for numeric data. SELECTAVG(sal), MAX(sal), MIN(sal), SUM(sal) FROMemp WHEREjob LIKE 'SALES%'

Using MIN and MAX Functions You can use MIN and MAX for any datatype. SELECTMIN(hiredate), MAX(hiredate) FROMemp MIN(HIRED MAX(HIRED DEC JAN-83

Using the COUNT Function COUNT(*) SELECTCOUNT(*) FROMemp WHEREdeptno = 30 COUNT(*) returns the number of rows in a table.

Using the COUNT Function COUNT(expr) returns the number of nonnull rows. SELECTCOUNT(comm) FROMemp WHEREdeptno = 30 COUNT(COMM)

Group Functions and Null Values Group functions ignore null values in the column. SELECTAVG(comm) FROM emp AVG(COMM)

Using the ISNULL Function with Group Functions The ISNULL function forces group functions to include null values. SELECT AVG(ISNULL(comm,0)) COMMISSION FROM emp COMMISSION

Creating Groups of Data EMP “average salary in EMP table for each department” DEPTNO SAL DEPTNO AVG(SAL)

Creating Groups of Data: GROUP BY Clause SELECTcolumn, group_function(column) FROMtable [WHEREcondition] [GROUP BYgroup_by_expression] [ORDER BYcolumn] Divide rows in a table into smaller groups by using the GROUP BY clause.

Using the GROUP BY Clause All columns in the SELECT list that are not in group functions must be in the GROUP BY clause. SELECT deptno, AVG(sal) FROM emp GROUP BY deptno DEPTNO AVG(SAL)

Using the GROUP BY Clause The GROUP BY column does not have to be in the SELECT list. SELECT AVG(sal) FROM emp GROUP BY deptno AVG(SAL)

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

Using the GROUP BY Clause on Multiple Columns SELECT deptno, job, sum(sal) FROM emp GROUP BY deptno, job DEPTNO JOB SUM(SAL) CLERK MANAGER PRESIDENT ANALYST CLERK rows selected.

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. SELECTdeptno, COUNT(ename) FROMemp SELECTdeptno, COUNT(ename) FROMemp Server: Msg 8118, Level 16, State 1, Line 1 Column 'emp.DEPTNO' is invalid in the select list because it is not contained in an aggregate function and there is no GROUP BY clause. Server: Msg 8118, Level 16, State 1, Line 1 Column 'emp.DEPTNO' is invalid in the select list because it is not contained in an aggregate function and there is no GROUP BY clause. Column missing in the GROUP BY clause

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. SELECTdeptno, AVG(sal) FROM emp WHEREAVG(sal) > 2000 GROUP BYdeptno SELECTdeptno, AVG(sal) FROM emp WHEREAVG(sal) > 2000 GROUP BYdeptno Server: Msg 147, Level 15, State 1, Line 3 An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference. Server: Msg 147, Level 15, State 1, Line 3 An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference. Cannot use the WHERE clause to restrict groups to restrict groups Cannot use the WHERE clause to restrict groups to restrict groups

Excluding Group Results “maximum salary per department greater than $2900” EMP DEPTNO SAL DEPTNO MAX(SAL)

Excluding Group Results: HAVING Clause Use the HAVING clause to restrict groups Rows are grouped. The group function is applied. Groups matching the HAVING clause are displayed. Use the HAVING clause to restrict groups Rows are grouped. The group function is applied. Groups matching the HAVING clause are displayed. SELECTcolumn, group_function FROMtable [WHEREcondition] [GROUP BYgroup_by_expression] [HAVINGgroup_condition] [ORDER BYcolumn]

Using the HAVING Clause SELECT deptno, max(sal) FROM emp GROUP BY deptno HAVING max(sal)>2900 DEPTNO MAX(SAL)

Using the HAVING Clause SELECT job, SUM(sal) PAYROLL FROM emp WHERE job NOT LIKE 'SALES%' GROUP BY job HAVING SUM(sal)>5000 ORDER BY SUM(sal) JOB PAYROLL ANALYST 6000 MANAGER 8275

Nesting Group Functions SELECT max(avg(sal)) FROM emp GROUP BY deptno MAX(AVG(SAL)) Display the maximum average salary.

SummarySummary SELECTcolumn, group_function(column) FROMtable [WHEREcondition] [GROUP BYgroup_by_expression] [HAVINGgroup_condition] [ORDER BYcolumn] Order of evaluation of the clauses: – WHERE clause – GROUP BY clause – HAVING clause Order of evaluation of the clauses: – WHERE clause – GROUP BY clause – HAVING clause

Displaying Data from Multiple Tables

ObjectivesObjectives After completing this lesson, you should be able to do the following: – Write SELECT statements to access data from more than one table using equality and nonequality joins – View data that generally does not meet a join condition by using outer joins – Join a table to itself After completing this lesson, you should be able to do the following: – Write SELECT statements to access data from more than one table using equality and nonequality joins – View data that generally does not meet a join condition by using outer joins – Join a table to itself

EMPNO DEPTNO LOC NEW YORK CHICAGO NEW YORK DALLAS CHICAGO CHICAGO rows selected. EMPNO DEPTNO LOC NEW YORK CHICAGO NEW YORK DALLAS CHICAGO CHICAGO rows selected. Obtaining Data from Multiple Tables EMPDEPT EMPNOENAME...DEPTNO KING BLAKE MILLER DEPTNO DNAME LOC ACCOUNTINGNEW YORK 20RESEARCHDALLAS 30SALESCHICAGO 40OPERATIONSBOSTON

What Is a Join? Use a join to query data from more than one table. – Write the join condition in the WHERE clause. – Prefix the column name with the table name when the same column name appears in more than one table. Use a join to query data from more than one table. – Write the join condition in the WHERE clause. – Prefix the column name with the table name when the same column name appears in more than one table. SELECTtable1.column, table2.column FROMtable1, table2 WHEREtable1.column1 = table2.column2 SELECTtable1.column, table2.column FROMtable1, table2 WHEREtable1.column1 = table2.column2

Cartesian Product – A Cartesian product is formed when: A join condition is omitted A join condition is invalid All rows in the first table are joined to all rows in the second table – To avoid a Cartesian product, always include a valid join condition in a WHERE clause. – A Cartesian product is formed when: A join condition is omitted A join condition is invalid All rows in the first table are joined to all rows in the second table – To avoid a Cartesian product, always include a valid join condition in a WHERE clause.

Generating a Cartesian Product ENAME DNAME KINGACCOUNTING BLAKE ACCOUNTING... KINGRESEARCH BLAKE RESEARCH rows selected. ENAME DNAME KINGACCOUNTING BLAKE ACCOUNTING... KINGRESEARCH BLAKE RESEARCH rows selected. EMP (14 rows) DEPT (4 rows) EMPNOENAME...DEPTNO KING BLAKE MILLER EMPNOENAME...DEPTNO KING BLAKE MILLER DEPTNO DNAME LOC ACCOUNTINGNEW YORK 20RESEARCHDALLAS 30SALESCHICAGO 40OPERATIONSBOSTON DEPTNO DNAME LOC ACCOUNTINGNEW YORK 20RESEARCHDALLAS 30SALESCHICAGO 40OPERATIONSBOSTON “Cartesian product: 14*4=56 rows”

Types of Joins Equijoin Non-equijoin Outer join Self join

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 20 RESEARCHDALLAS 30 SALES CHICAGO 40 OPERATIONSBOSTON 4 rows selected. Foreign key Primary key

Retrieving Records with Equijoins SELECT emp.empno, emp.ename, emp.deptno, dept.deptno, dept.loc FROM emp, dept WHERE emp.deptno=dept.deptno EMPNO ENAME DEPTNO DEPTNO LOC KING NEW YORK 7698 BLAKE CHICAGO 7782 CLARK NEW YORK 7566 JONES DALLAS rows selected.

Non-EquijoinsNon-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

Retrieving Records with Non-Equijoins ENAME SAL GRADE JAMES SMITH ADAMS rows selected. SELECT e.ename, e.sal, s.grade FROMemp e, salgrade s WHERE e.sal BETWEEN s.losal AND s.hisal

Types of Join 1. Inner Join 2. Outer Join 3. Self Join

Inner Join In this type of join, Records in the joined tables must have the same value for fields that are joined. For example List the employees who work in ‘ACCOUNTING’ department.

Example SELECT ename, dname FROMemp INNER JOIN dept ON emp.deptno=dept.deptno WHERE UPPER(dname)='ACCOUNTING'

OUTER JOIN In this type of join, all records from one table are listed in the output even if no joining record is available in the joined table. Outer joins are categorized as left outer join and right outer join. For example, List all employees along with their department names or List all departments along with the employee names working in these departments.

Outer Joins – You use an outer join to also see rows that do not usually meet the join condition. SELECTtable1.column, table2.column FROMtable1 LEFT OUTER JOIN table2 ON table1.column = table2.column SELECTtable1.column, table2.column FROMtable1 LEFT OUTER JOIN table2 ON table1.column = table2.column SELECTtable1.column, table2.column FROMtable1 RIGHT OUTER JOIN table2 ON table1.column = table2.column SELECTtable1.column, table2.column FROMtable1 RIGHT OUTER JOIN table2 ON table1.column = table2.column

Outer Joins – Outer join operator is Left outer (*=) Right outer (=*) – Outer join operator is Left outer (*=) Right outer (=*) SELECTtable1.column, table2.column FROMtable1, table2 WHEREtable1.column *= table2.column SELECTtable1.column, table2.column FROMtable1, table2 WHEREtable1.column *= table2.column SELECTtable1.column, table2.column FROMtable1, table2 WHEREtable1.column =* table2.column SELECTtable1.column, table2.column FROMtable1, table2 WHEREtable1.column =* table2.column

Outer Joins EMP DEPT No employee in the OPERATIONS department ENAMEDEPTNO KING10 BLAKE30 CLARK10 JONES20... DEPTNO DNAME ACCOUNTING 20RESEARCH... 40OPERATIONS

Using Outer Joins SELECTe.ename, d.deptno, d.dname FROMemp e LEFT OUTER JOIN dept d ON e.deptno = d.deptno ORDER BYe.deptno ENAME DEPTNO DNAME KING 10 ACCOUNTING CLARK 10 ACCOUNTING OPERATIONS 15 rows selected.

Example 1 SELECTe.ename, d.deptno, d.dname FROMemp e LEFT OUTER JOIN dept d ON e.deptno = d.deptno ORDER BYd.deptno — OR— SELECTe.ename, d.deptno, d.dname FROMemp e, dept d WHEREe.deptno *= d.deptno ORDER BYd.deptno

SELECTe.ename, d.deptno, d.dname FROMemp e RIGHT OUTER JOIN dept d ON e.deptno = d.deptno ORDER BYd.deptno — OR— SELECTe.ename, d.deptno, d.dname FROMemp e, dept d WHEREe.deptno =* d.deptno ORDER BYd.deptno Example 2

Full Outer Join FULL OUTER JOIN includes all rows from both tables, regardless of whether or not the other table has a matching value.

Full Outer Join SELECTe.ename, d.deptno, d.dname FROMemp e FULL OUTER JOIN dept d ON e.deptno = d.deptno ORDER BYd.deptno

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

Self Join There are the times when joining of one table with itself is required. For example, suppose we have an employee’s table having manager’s ID also and we want to list the employee name with his manager name. Then we will require the usage of employee table twice. For such situations Self join is used as shown in the example.

Example SELECT worker.ename + ' works for ' + manager.ename FROM emp worker, emp manager WHERE worker.mgr = manager.empno

Joining a Table to Itself BLAKE works for KING CLARK works for KING JONES works for KING MARTIN works for BLAKE rows selected BLAKE works for KING CLARK works for KING JONES works for KING MARTIN works for BLAKE rows selected. SELECT worker.ename + ' works for ' + manager.ename FROM emp worker INNER JOIN emp manager ON worker.mgr = manager.empno

Qualifying Ambiguous Column Names – Use table prefixes to qualify column names that are in multiple tables. – Improve performance by using table prefixes. – Distinguish columns that have identical names but reside in different tables by using column aliases. – Use table prefixes to qualify column names that are in multiple tables. – Improve performance by using table prefixes. – Distinguish columns that have identical names but reside in different tables by using column aliases.

Additional Search Conditions Using the AND Operator EMPDEPT EMPNO ENAME DEPTNO KING BLAKE CLARK JONES MARTIN ALLEN TURNER JAMES WARD FORD SMITH rows selected. DEPTNO DNAME LOC ACCOUNTINGNEW YORK 20 RESEARCHDALLAS 30 SALES CHICAGO 40OPERATIONSBOSTON 4 rows selected.

Using Table Aliases Simplify queries by using table aliases. SELECT emp.empno, emp.ename, emp.deptno, dept.deptno, dept.loc FROM emp, dept WHERE emp.deptno=dept.deptno; SELECT e.empno, e.ename, e.deptno, d.deptno, d.loc FROM emp e, dept d WHERE e.deptno=d.deptno;

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

SummarySummary Equijoin Non-equijoin Outer join Self join SELECTtable1.column, table2.column FROMtable1, table2 WHEREtable1.column1 = table2.column2; SELECTtable1.column, table2.column FROMtable1, table2 WHEREtable1.column1 = table2.column2;

This predicate is used to limit the output to the top most n records only, Where n must be an integer. For Example SELECTtop 3 deptno, ename FROMemp Top n

SubqueriesSubqueries

ObjectivesObjectives After completing this lesson, you should be able to do the following: – Describe the types of problems that subqueries can solve – Define subqueries – List the types of subqueries – Write single-row and multiple-row subqueries After completing this lesson, you should be able to do the following: – Describe the types of problems that subqueries can solve – Define subqueries – List the types of subqueries – Write single-row and multiple-row subqueries

Using a Subquery to Solve a Problem “Who has a salary greater than Jones’?” “Which employees have a salary greater than Jones’ salary?” Main Query ? “What is Jones’ salary?” ? Subquery

SubqueriesSubqueries – 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)

2975 SELECT ename FROM emp WHERE sal > (SELECT sal FROM emp WHERE empno=7566) Using a Subquery ENAME KING FORD SCOTT ENAME KING FORD SCOTT

Guidelines for Using Subqueries – Enclose subqueries in parentheses. – Place subqueries on the right side of the comparison operator. – Do not add an ORDER BY clause to a subquery. – Use single-row operators with single-row subqueries. – Use multiple-row operators with multiple- row subqueries. – Enclose subqueries in parentheses. – Place subqueries on the right side of the comparison operator. – Do not add an ORDER BY clause to a subquery. – Use single-row operators with single-row subqueries. – Use multiple-row operators with multiple- row subqueries.

Types of Subqueries – Single-row subquery Main query Subquery returns CLERK Multiple-row subquery CLERKMANAGER Main query Subquery returns Multiple-column subquery CLERK 7900 MANAGER 7698 Main query Subquery returns

Single-Row Subqueries – Return only one row – Use single-row comparison operators – Return only one row – Use single-row comparison operators Operator = > >= < <= <> Meaning Equal to Greater than Greater than or equal to Less than Less than or equal to Not equal to

Executing Single-Row Subqueries CLERK 1100 ENAME JOB MILLER CLERK ENAME JOB MILLER CLERK SELECT ename, job FROM emp WHERE job = (SELECT job FROM emp WHERE empno = 7369) AND sal > (SELECT sal FROMemp WHEREempno = 7876)

Using Group Functions in a Subquery 800 ENAME JOB SAL SMITH CLERK 800 ENAME JOB SAL SMITH CLERK 800 SELECTename, job, sal FROMemp WHEREsal = (SELECTMIN(sal) FROMemp)

HAVING Clause with Subqueries – Subqueries are executed first. – Results are returned into the HAVING clause of the main query. – Subqueries are executed first. – Results are returned into the HAVING clause of the main query. 800 SELECTdeptno, MIN(sal) FROMemp GROUP BYdeptno HAVINGMIN(sal) > (SELECTMIN(sal) FROMemp WHEREdeptno = 20)

What Is Wrong with This Statement? Server: Msg 512, Level 16, State 1, Line 1 Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=,, >= or when the subquery is used as an expression. Server: Msg 512, Level 16, State 1, Line 1 Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=,, >= or when the subquery is used as an expression. SELECT empno, ename FROM emp WHERE sal = (SELECT MIN(sal) FROM emp GROUP BY deptno) Single-row operator with multiple-row subquery

Will This Statement Work? no rows selected Subquery returns no values SELECT ename, job FROM emp WHERE job = (SELECTjob FROMemp WHEREename='SMYTHE')

Multiple-Row Subqueries – Return more than one row – Use multiple-row comparison operators – Return more than one row – Use multiple-row comparison operators Operator IN ANY ALL Meaning Equal to any member in the list Compare value to each value returned by the subquery Compare value to every value returned by the subquery

Using ANY Operator in Multiple-Row Subqueries EMPNO ENAME JOB MARTIN SALESMAN 7521 WARD SALESMAN EMPNO ENAME JOB MARTIN SALESMAN 7521 WARD SALESMAN SELECT empno, ename, job FROM emp WHERE sal < ANY (SELECTsal FROMemp WHEREjob = 'CLERK') AND job <> 'CLERK'

Using ALL Operator in Multiple-Row Subqueries EMPNO ENAME JOB KING PRESIDENT 7566 JONES MANAGER 7902 FORD ANALYST 7788 SCOTT ANALYST EMPNO ENAME JOB KING PRESIDENT 7566 JONES MANAGER 7902 FORD ANALYST 7788 SCOTT ANALYST SELECT empno, ename, job FROM emp WHERE sal > ALL (SELECTavg(sal) FROMemp GROUP BYdeptno)

SubquerySubquery SELECT ordid, prodid, qty FROM item WHERE prodid IN (SELECT prodid FROM item WHERE ordid = 605) ANDqty IN (SELECT qty FROM item WHERE ordid = 605) ANDordid <> 605 Display the order number, product number, and quantity of any item in which the product number and quantity match any product number and any quantity of an item in order 605.

SubquerySubquery SELECT ename, deptno, sal, comm FROM emp WHERE sal IN (SELECT sal FROM emp WHERE deptno = 30) AND ISNULL(comm,-1) IN (SELECT ISNULL(comm,-1) FROM emp WHERE deptno = 30) Display the name, department number, salary, and commission of any employee whose salary and commission matches the commission and salary of any employee in department 30.

Null Values in a Subquery SELECTemployee.ename FROM emp employee WHERE employee.empno NOT IN (SELECT manager.mgr FROM emp manager) no rows selected.

SELECTemployee.ename FROM emp employee WHERE employee.empno NOT IN (SELECT ISNULL(manager.mgr,0) FROM emp manager)

Using a Subquery in the FROM Clause ENAME SAL DEPTNO SALAVG KING JONES SCOTT rows selected. ENAME SAL DEPTNO SALAVG KING JONES SCOTT rows selected. SELECT a.ename, a.sal, a.deptno, b.salavg FROM emp a, (SELECT deptno, avg(sal) salavg FROM emp GROUP BY deptno) b WHERE a.deptno = b.deptno AND a.sal > b.salavg

Some Data Types

Integers bigint Integer (whole number) data from -2^63 ( ) through 2^63-1 ( ). int Integer (whole number) data from -2^31 (- 2,147,483,648) through 2^ (2,147,483,647). smallint Integer data from 2^15 (-32,768) through 2^ (32,767). tinyint Integer data from 0 through 255.

bit Integer data with either a 1 or 0 value. decimal and numeric decimal Fixed precision and scale numeric data from -10^38 +1 through 10^38 –1. numeric Functionally equivalent to decimal.

money and smallmoney money Monetary data values from -2^63 (- 922,337,203,685, ) through 2^ (+922,337,203,685, ), with accuracy to a ten-thousandth of a monetary unit. smallmoney Monetary data values from -214, through +214, , with accuracy to a ten-thousandth of a monetary unit.

datetime and smalldatetime datetime Date and time data from January 1, 1753, through December 31, 9999, with an accuracy of three-hundredths of a second, or 3.33 milliseconds. smalldatetime Date and time data from January 1, 1900, through June 6, 2079, with an accuracy of one minute.

Character Strings char Fixed-length non-Unicode character data with a maximum length of 8,000 characters. varchar Variable-length non-Unicode data with a maximum of 8,000 characters. text Variable-length non-Unicode data with a maximum length of 2^ (2,147,483,647) characters.