Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Single-Row Functions. SQL Functions FunctionInput arg 1 arg 2 arg n Function performs action OutputResultvalue."— Presentation transcript:

1 Single-Row Functions

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

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

4 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,...])

5 Single-Row Functions Conversion CharacterNumber Date Single-rowfunctions

6 Character Functions Characterfunctions LOWERUPPERSUBSTRINGLENLTRIMRTRIMLEFTRIGHT Case conversion functions Character manipulation functions

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

8 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 --------- ---------- --------- 7698 BLAKE 30 EMPNO ENAME DEPTNO --------- ---------- --------- 7698 BLAKE 30 SELECTempno, ename, deptno FROMemp WHERE LOWER(ename) = 'blake'

9 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

10 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

11 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) --------------- -------------- ----------------- 45.92 46 50

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

13 Aggregating Data Using Group Functions

14 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 --------- 10 2450 10 5000 10 1300 20 800 20 1100 20 3000 20 2975 30 1600 30 2850 30 1250 30 950 30 1500 30 1250 MAX(SAL) --------- 5000

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

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

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

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

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

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

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

22 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 ---------- 157.14286

23 Creating Groups of Data EMP “average salary in EMP table for each department” 2916.6667 2916.6667 2175 2175 1566.6667 1566.6667 DEPTNO SAL --------- 10 2450 10 5000 10 1300 20 800 20 1100 20 3000 20 2975 30 1600 30 2850 30 1250 30 950 30 1500 30 1250 DEPTNO AVG(SAL) ------- --------- 10 2916.6667 20 2175 30 1566.6667

24 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.

25 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) --------- 10 2916.6667 20 2175 30 1566.6667

26 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) --------- 2916.6667 2175 1566.6667

27 Grouping by More Than One Column EMP “sum salaries in the EMP table for each job, grouped by department” DEPTNO JOB SAL --------- --------- --------- 10 MANAGER 2450 10 PRESIDENT 5000 10 CLERK 1300 20 CLERK 800 20 CLERK 1100 20 ANALYST 3000 20 MANAGER 2975 30 SALESMAN 1600 30 MANAGER 2850 30 SALESMAN 1250 30 CLERK 950 30 SALESMAN 1500 30 SALESMAN 1250 JOB SUM(SAL) --------- CLERK 1300 MANAGER 2450 PRESIDENT 5000 ANALYST 6000 CLERK 1900 MANAGER 2975 CLERK 950 MANAGER 2850 SALESMAN 5600 DEPTNO -------- 10 20 30

28 Using the GROUP BY Clause on Multiple Columns SELECT deptno, job, sum(sal) FROM emp GROUP BY deptno, job DEPTNO JOB SUM(SAL) --------- --------- --------- 10 CLERK 1300 10 MANAGER 2450 10 PRESIDENT 5000 20 ANALYST 6000 20 CLERK 1900... 9 rows selected.

29 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

30 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

31 Excluding Group Results “maximum salary per department greater than $2900” EMP 5000 3000 2850 DEPTNO SAL --------- 10 2450 10 5000 10 1300 20 800 20 1100 20 3000 20 2975 30 1600 30 2850 30 1250 30 950 30 1500 30 1250 DEPTNO MAX(SAL) --------- 10 5000 20 3000

32 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]

33 Using the HAVING Clause SELECT deptno, max(sal) FROM emp GROUP BY deptno HAVING max(sal)>2900 DEPTNO MAX(SAL) --------- 10 5000 20 3000

34 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

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

36 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

37 Displaying Data from Multiple Tables

38 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

39 EMPNO DEPTNO LOC ----- ------- -------- 7839 10 NEW YORK 7698 30 CHICAGO 7782 10 NEW YORK 7566 20 DALLAS 7654 30 CHICAGO 7499 30 CHICAGO... 14 rows selected. EMPNO DEPTNO LOC ----- ------- -------- 7839 10 NEW YORK 7698 30 CHICAGO 7782 10 NEW YORK 7566 20 DALLAS 7654 30 CHICAGO 7499 30 CHICAGO... 14 rows selected. Obtaining Data from Multiple Tables EMPDEPT EMPNOENAME...DEPTNO -----------...------ 7839KING... 10 7698BLAKE... 30... 7934MILLER... 10 DEPTNO DNAME LOC ------ ------------------ 10ACCOUNTINGNEW YORK 20RESEARCHDALLAS 30SALESCHICAGO 40OPERATIONSBOSTON

40 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

41 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.

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

43 Types of Joins Equijoin Non-equijoin Outer join Self join

44 What Is an Equijoin? EMP DEPT EMPNO ENAME DEPTNO ------ ------- ------- 7839 KING 10 7698 BLAKE 30 7782 CLARK 10 7566 JONES 20 7654 MARTIN 30 7499 ALLEN 30 7844 TURNER 30 7900 JAMES 30 7521 WARD 30 7902 FORD 20 7369 SMITH 20... 14 rows selected. DEPTNO DNAME LOC ------- ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCHDALLAS 30 SALES CHICAGO 40 OPERATIONSBOSTON 4 rows selected. Foreign key Primary key

45 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 ----- ------ ------ ------ --------- 7839 KING 10 10 NEW YORK 7698 BLAKE 30 30 CHICAGO 7782 CLARK 10 10 NEW YORK 7566 JONES 20 20 DALLAS... 14 rows selected.

46 Non-EquijoinsNon-Equijoins EMPSALGRADE “salary in the EMP table is between low salary and high salary in the SALGRADE table” EMPNO ENAME SAL ------ ------- ------ 7839 KING 5000 7698 BLAKE 2850 7782 CLARK 2450 7566 JONES 2975 7654 MARTIN 1250 7499 ALLEN 1600 7844 TURNER 1500 7900 JAMES 950... 14 rows selected. GRADE LOSAL HISAL ----- ----- ------ 1 7001200 2 12011400 3 14012000 420013000 5 30019999

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

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

49 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.

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

51 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.

52 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

53 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

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

55 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... 40 OPERATIONS 15 rows selected.

56 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

57 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

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

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

60 Self Joins EMP (WORKER) EMP (MANAGER) “MGR in the WORKER table is equal to EMPNO in the MANAGER table” EMPNOENAME MGR --------------- 7839KING 7698BLAKE7839 7782CLARK7839 7566JONES7839 7654MARTIN7698 7499ALLEN7698 EMPNOENAME ------------- 7839KING 7698BLAKE

61 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.

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

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

64 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.

65 Additional Search Conditions Using the AND Operator EMPDEPT EMPNO ENAME DEPTNO ------ ------- ------- 7839 KING 10 7698 BLAKE 30 7782 CLARK 10 7566 JONES 20 7654 MARTIN 30 7499 ALLEN 30 7844 TURNER 30 7900 JAMES 30 7521 WARD 30 7902 FORD 20 7369 SMITH 20... 14 rows selected. DEPTNO DNAME LOC ------ ----------------- 10 ACCOUNTINGNEW YORK 20 RESEARCHDALLAS 30 SALES CHICAGO 40OPERATIONSBOSTON 4 rows selected.

66 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;

67 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 107... 9 rows selected. NAMECUSTID ----------------- JOCKSPORTS 100 TKB SPORT SHOP 101 VOLLYRITE 102 JUST TENNIS 103 K+T SPORTS 105 SHAPE UP 106 WOMENS SPORTS 107... 9 rows selected. CUSTOMER CUSTID ORDID ------- 101 610 102 611 104 612 106 601 102 602 106 604 106 605... 21 rows selected. CUSTID ORDID ------- 101 610 102 611 104 612 106 601 102 602 106 604 106 605... 21 rows selected.ORD ORDID ITEMID ------ ------- 610 3 611 1 612 1 601 1 602 1... 64 rows selected. ORDID ITEMID ------ ------- 610 3 611 1 612 1 601 1 602 1... 64 rows selected.ITEM

68 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;

69 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

70 SubqueriesSubqueries

71 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

72 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

73 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)

74 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

75 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.

76 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

77 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

78 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)

79 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)

80 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)

81 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

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

83 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

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

85 Using ALL Operator in Multiple-Row Subqueries 2916.6667 2175 1566.6667 EMPNO ENAME JOB --------- ---------- --------- 7839 KING PRESIDENT 7566 JONES MANAGER 7902 FORD ANALYST 7788 SCOTT ANALYST EMPNO ENAME JOB --------- ---------- --------- 7839 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)

86 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.

87 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.

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

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

90 Using a Subquery in the FROM Clause ENAME SAL DEPTNO SALAVG ---------- --------- --------- ---------- KING 5000 10 2916.6667 JONES 2975 20 2175 SCOTT 3000 20 2175... 6 rows selected. ENAME SAL DEPTNO SALAVG ---------- --------- --------- ---------- KING 5000 10 2916.6667 JONES 2975 20 2175 SCOTT 3000 20 2175... 6 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

91 Some Data Types

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

93 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.

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

95 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.

96 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^31 - 1 (2,147,483,647) characters.


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

Similar presentations


Ads by Google