Single-Row Functions Single-Row Functions
Jan 03, 2016
Single-Row FunctionsSingle-Row FunctionsSingle-Row FunctionsSingle-Row Functions
SQL FunctionsSQL FunctionsSQL FunctionsSQL Functions
FunctionFunctionInputInput
arg 1arg 1
arg 2arg 2
arg arg nn
Function Function performs actionperforms action
OutputOutput
ResultResultvaluevalue
Two Types of SQL FunctionsTwo Types of SQL FunctionsTwo Types of SQL FunctionsTwo Types of SQL Functions
FunctionsFunctions
Single-row Single-row functionsfunctions
Multiple-rowMultiple-rowfunctionsfunctions
Single-Row FunctionsSingle-Row FunctionsSingle-Row FunctionsSingle-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,...])function_name (column|expression, [arg1, arg2,...])
Single-Row FunctionsSingle-Row FunctionsSingle-Row FunctionsSingle-Row Functions
ConversionConversion
CharacterCharacter NumberNumber
DateDate
Single-row Single-row functionsfunctions
Character FunctionsCharacter FunctionsCharacter FunctionsCharacter Functions
CharacterCharacterfunctionsfunctions
LOWERLOWER
UPPERUPPER
SUBSTRINGSUBSTRING
LENLEN
LTRIMLTRIM
RTRIMRTRIM
LEFTLEFT
RIGHTRIGHT
Case conversion Case conversion functionsfunctions
Character manipulationCharacter manipulationfunctionsfunctions
Function Result
Case Conversion FunctionsCase Conversion FunctionsCase Conversion FunctionsCase Conversion Functions
Convert case for character stringsConvert case for character strings
LOWER('SQL Course')
UPPER('SQL Course')
sql course
SQL COURSE
Using Case Conversion Using Case Conversion FunctionsFunctions
Using Case Conversion Using Case Conversion FunctionsFunctions
Display the employee number, name, and department number for employee Blake.
Display the employee number, name, and department number for employee Blake.
SELECT empno, ename, deptno FROM emp WHERE ename = 'blake' no rows selectedno rows selected
SELECT empno, ename, deptno FROM emp WHERE ename = 'blake' no rows selectedno rows selected
EMPNO ENAME DEPTNO--------- ---------- --------- 7698 BLAKE 30
EMPNO ENAME DEPTNO--------- ---------- --------- 7698 BLAKE 30
SELECT empno, ename, deptno FROM emp WHERE LOWER(ename) = 'blake'
SUBSTRING('String',1,3)
LEN(‘String’)
LTRIM(‘ String ’)
RTRIM(‘ String ’)
LEFT(‘String’, 3)
RIGHT(‘String’, 3)
Str
6
String
String
Str
ing
Function Result
Character Manipulation Character Manipulation FunctionsFunctions
Character Manipulation Character Manipulation FunctionsFunctions
Manipulate character stringsManipulate character strings
Using the Character Using the Character Manipulation FunctionsManipulation Functions
Using the Character Using the Character Manipulation FunctionsManipulation 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 FunctionUsing the ROUND FunctionUsing the ROUND FunctionUsing 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
SELECT FLOOR(123.45), FLOOR(-123.45), FLOOR(123.95)
Using the FLOOR,CEILING Using the FLOOR,CEILING FunctionsFunctions
Using the FLOOR,CEILING Using the FLOOR,CEILING FunctionsFunctions
SELECT CEILING(123.45), CEILING(-123.45), CEILING(0.0)
Aggregating Data Aggregating Data Using Group FunctionsUsing Group Functions
Aggregating Data Aggregating Data Using Group FunctionsUsing Group Functions
What Are Group Functions?What Are Group Functions?What Are Group Functions?What Are Group Functions? Group functions operate on sets of rows to
give one result per group. Group functions operate on sets of rows to
give one result per group.EMPEMP
““maximum maximum salary in salary in
the EMP table”the EMP table”
DEPTNO SAL--------- --------- 10 2450 10 5000 10 1300 20 800 20 1100 20 3000 20 3000 20 2975 30 1600 30 2850 30 1250 30 950 30 1500 30 1250
MAX(SAL)
---------
5000
Types of Group FunctionsTypes of Group FunctionsTypes of Group FunctionsTypes of Group Functions
– AVG – COUNT – MAX– MIN – SUM
– AVG – COUNT – MAX– MIN – SUM
Using Group FunctionsUsing Group FunctionsUsing Group FunctionsUsing Group Functions
SELECT [column,] group_function(column)FROM table[WHERE condition][GROUP BY column][ORDER BY column]
Using AVG and SUM Using AVG and SUM FunctionsFunctions
Using AVG and SUM Using AVG and SUM FunctionsFunctions
AVG(SAL) MAX(SAL) MIN(SAL) SUM(SAL)-------- --------- --------- --------- 1400 1600 1250 5600
You can use AVG and SUM for numeric data.You can use AVG and SUM for numeric data.
SELECT AVG(sal), MAX(sal),MIN(sal), SUM(sal)
FROM empWHERE job LIKE 'SALES%'
Using MIN and MAX Using MIN and MAX FunctionsFunctions
Using MIN and MAX Using MIN and MAX FunctionsFunctions
You can use MIN and MAX for any datatype.
You can use MIN and MAX for any datatype.
SELECT MIN(hiredate), MAX(hiredate)FROM emp
MIN(HIRED MAX(HIRED--------- ---------17-DEC-80 12-JAN-83
Using the COUNT FunctionUsing the COUNT FunctionUsing the COUNT FunctionUsing the COUNT Function
COUNT(*)--------- 6
SELECT COUNT(*)FROM empWHERE deptno = 30
COUNT(*) returns the number of rows in a table.
COUNT(*) returns the number of rows in a table.
Using the COUNT FunctionUsing the COUNT FunctionUsing the COUNT FunctionUsing the COUNT Function
COUNT(expr) returns the number of nonnull rows.
COUNT(expr) returns the number of nonnull rows.
SELECT COUNT(comm)FROM empWHERE deptno = 30
COUNT(COMM)----------- 4
Group Functions and Null Group Functions and Null ValuesValues
Group Functions and Null Group Functions and Null ValuesValues
Group functions ignore null values in the column.
Group functions ignore null values in the column.
SELECT AVG(comm)FROM emp
AVG(COMM)--------- 550
Using the ISNULL Function Using the ISNULL Function with Group Functionswith Group Functions
Using the ISNULL Function Using the ISNULL Function with Group Functionswith Group Functions
The ISNULL function forces group functions to include null values.
The ISNULL function forces group functions to include null values.
SELECT AVG(ISNULL(comm,0)) COMMISSION FROM emp
COMMISSION---------- 157.14286
Creating Groups of Data Creating Groups of Data Creating Groups of Data Creating Groups of Data EMPEMP
““averageaveragesalary salary in EMPin EMPtable table
for each for each department”department”
2916.66672916.6667
21752175
1566.66671566.6667
DEPTNO SAL--------- --------- 10 2450 10 5000 10 1300 20 800 20 1100 20 3000 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
Creating Groups of Data: Creating Groups of Data: GROUP BY ClauseGROUP BY Clause
Creating Groups of Data: Creating Groups of Data: GROUP BY ClauseGROUP BY Clause
SELECT column, group_function(column)FROM table[WHERE condition][GROUP BY group_by_expression][ORDER BY column]
Divide rows in a table into smaller groups by using the GROUP BY clause.
Divide rows in a table into smaller groups by using the GROUP BY clause.
Using the GROUP BY Clause Using the GROUP BY Clause 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.
All columns in the SELECT list that are not in group functions must be in the GROUP BY clause.
SELECT deptno, AVG(sal)FROM empGROUP BY deptno
DEPTNO AVG(SAL)--------- --------- 10 2916.6667 20 2175 30 1566.6667
Using the GROUP BY Clause Using the GROUP BY Clause Using the GROUP BY Clause Using the GROUP BY Clause The GROUP BY column does not have
to be in the SELECT list.
The GROUP BY column does not have to be in the SELECT list.
SELECT AVG(sal)FROM empGROUP BY deptno
AVG(SAL)--------- 2916.6667 21751566.6667
Grouping by More Grouping by More Than One ColumnThan One ColumnGrouping by More Grouping by More Than One ColumnThan One Column
EMPEMP
““sum salaries in sum salaries in the EMP tablethe EMP tablefor each job, for each job, grouped by grouped by department”department”
DEPTNO JOB SAL
--------- --------- ---------
10 MANAGER 2450
10 PRESIDENT 5000
10 CLERK 1300
20 CLERK 800
20 CLERK 1100
20 ANALYST 3000
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
10
10
20
20
20
30
30
30
Using the GROUP BY Clause Using the GROUP BY Clause on Multiple Columnson Multiple Columns
Using the GROUP BY Clause Using the GROUP BY Clause on Multiple Columnson Multiple Columns
SELECT deptno, job, sum(sal)FROM empGROUP 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.
Illegal Queries Illegal Queries Using Group FunctionsUsing Group Functions
Illegal Queries Illegal Queries Using Group FunctionsUsing Group Functions
Any column or expression in the SELECT list that is not an aggregate function must be in the GROUP BY clause.
Any column or expression in the SELECT list that is not an aggregate function must be in the GROUP BY clause.SELECT deptno, COUNT(ename)FROM emp
SELECT deptno, COUNT(ename)FROM emp
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
Column missing in the GROUP BY clause
Column missing in the GROUP BY clause
Column missing in the GROUP BY clause
Illegal Queries Illegal Queries Using Group FunctionsUsing Group Functions
Illegal Queries Illegal Queries Using Group FunctionsUsing 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.
SELECT deptno, AVG(sal)FROM empWHERE AVG(sal) > 2000GROUP BY deptno
SELECT deptno, AVG(sal)FROM empWHERE AVG(sal) > 2000GROUP BY deptno
Server: Msg 147, Level 15, State 1, Line 3An 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 3An 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
Cannot use the WHERE clause
to
restrict groups
to restrict groups
Cannot use the WHERE clause
Cannot use the WHERE clause
to
restrict groups
to restrict groups
Excluding Group ResultsExcluding Group ResultsExcluding Group ResultsExcluding Group Results
““maximummaximumsalarysalary
per departmentper departmentgreater thangreater than
$2900”$2900”
EMPEMP
50005000
30003000
28502850
DEPTNO SAL
--------- ---------
10 2450
10 5000
10 1300
20 800
20 1100
20 3000
20 3000
20 2975
30 1600
30 2850
30 1250
30 950
30 1500
30 1250
DEPTNO MAX(SAL)
--------- ---------
10 5000
20 3000
Excluding Group Results: Excluding Group Results: HAVING ClauseHAVING Clause
Excluding Group Results: Excluding Group Results: HAVING ClauseHAVING 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.SELECT column, group_functionFROM table[WHERE condition][GROUP BY group_by_expression][HAVING group_condition][ORDER BY column]
Using the HAVING ClauseUsing the HAVING ClauseUsing the HAVING ClauseUsing the HAVING Clause
SELECT deptno, max(sal)FROM empGROUP BY deptnoHAVING max(sal)>2900
DEPTNO MAX(SAL)--------- --------- 10 5000 20 3000
Using the HAVING ClauseUsing the HAVING ClauseUsing the HAVING ClauseUsing the HAVING Clause
SELECT job, SUM(sal) PAYROLLFROM empWHERE job NOT LIKE 'SALES%'GROUP BY jobHAVING SUM(sal)>5000ORDER BY SUM(sal)
JOB PAYROLL--------- ---------ANALYST 6000MANAGER 8275
Nesting Group FunctionsNesting Group FunctionsNesting Group FunctionsNesting Group Functions
SELECT max(avg(sal))FROM empGROUP BY deptno
MAX(AVG(SAL))------------- 2916.6667
Display the maximum average salary. Display the maximum average salary.
SummarySummarySummarySummarySELECT column, group_function(column)FROM table[WHERE condition][GROUP BY group_by_expression][HAVING group_condition][ORDER BY column]
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 Displaying Data from Multiple Tablesfrom Multiple Tables
Displaying Data Displaying Data from Multiple Tablesfrom Multiple Tables
ObjectivesObjectivesObjectivesObjectives
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----- ------- -------- 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 TablesObtaining Data from Multiple TablesObtaining Data from Multiple TablesObtaining Data from Multiple TablesEMP EMP DEPT DEPT EMPNO ENAME ... DEPTNO------ ----- ... ------ 7839 KING ... 10 7698 BLAKE ... 30 ... 7934 MILLER ... 10
DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON
What Is a Join?What Is a Join?What Is a Join?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.
SELECT table1.column, table2.columnFROM table1, table2WHERE table1.column1 = table2.column2
SELECT table1.column, table2.columnFROM table1, table2WHERE table1.column1 = table2.column2
Cartesian ProductCartesian ProductCartesian ProductCartesian 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 Generating a Cartesian ProductProduct
Generating a Cartesian Generating a Cartesian ProductProduct
ENAME DNAME------ ----------KING ACCOUNTINGBLAKE ACCOUNTING ...KING RESEARCHBLAKE RESEARCH...56 rows selected.
ENAME DNAME------ ----------KING ACCOUNTINGBLAKE ACCOUNTING ...KING RESEARCHBLAKE RESEARCH...56 rows selected.
EMP (14 rows) EMP (14 rows) DEPT (4 rows) DEPT (4 rows)
EMPNO ENAME ... DEPTNO------ ----- ... ------ 7839 KING ... 10 7698 BLAKE ... 30 ... 7934 MILLER ... 10
EMPNO ENAME ... DEPTNO------ ----- ... ------ 7839 KING ... 10 7698 BLAKE ... 30 ... 7934 MILLER ... 10
DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON
DEPTNO DNAME LOC ------ ---------- -------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON
““CartesianCartesianproduct: product:
14*4=56 rows”14*4=56 rows”
Types of JoinsTypes of JoinsTypes of JoinsTypes of Joins
EquijoinEquijoin Non-equijoinNon-equijoin Outer joinOuter join Self joinSelf join
What Is an Equijoin?What Is an Equijoin?What Is an Equijoin?What Is an Equijoin?EMP EMP DEPT 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 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON
4 rows selected.
Foreign keyForeign key Primary keyPrimary key
Retrieving Records Retrieving Records with Equijoinswith Equijoins
Retrieving Records Retrieving Records with Equijoinswith 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.
Non-EquijoinsNon-EquijoinsNon-EquijoinsNon-EquijoinsEMPEMP SALGRADESALGRADE
““salary in the EMP salary in the EMP table is between table is between low salary and high low salary and high salary in the SALGRADEsalary in the SALGRADEtable”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 700 12002 1201 14003 1401 20004 2001 30005 3001 9999
Retrieving Records Retrieving Records with Non-Equijoinswith Non-Equijoins
Retrieving Records Retrieving Records with Non-Equijoinswith Non-Equijoins
ENAME SAL GRADE---------- --------- ---------JAMES 950 1SMITH 800 1ADAMS 1100 1...14 rows selected.
SELECT e.ename, e.sal, s.grade
FROM emp e, salgrade s
WHERE e.sal
BETWEEN s.losal AND s.hisal
Types of Join Types of Join
1. Inner Join
2. Outer Join
3. Self Join
Inner JoinInner 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.
ExampleExample
SELECT ename, dname
FROM emp INNER JOIN dept
ON emp.deptno=dept.deptno
WHERE UPPER(dname)='ACCOUNTING'
OUTER JOINOUTER JOINIn 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 JoinsOuter JoinsOuter JoinsOuter Joins– You use an outer join to also see rows that
do not usually meet the join condition.– You use an outer join to also see rows that
do not usually meet the join condition.
SELECT table1.column, table2.column
FROM table1 LEFT OUTER JOIN table2
ON table1.column = table2.column
SELECT table1.column, table2.column
FROM table1 LEFT OUTER JOIN table2
ON table1.column = table2.column
SELECT table1.column, table2.column
FROM table1 RIGHT OUTER JOIN table2
ON table1.column = table2.column
SELECT table1.column, table2.column
FROM table1 RIGHT OUTER JOIN table2
ON table1.column = table2.column
Outer JoinsOuter JoinsOuter JoinsOuter Joins– Outer join operator is
Left outer (*=) Right outer (=*)
– Outer join operator is Left outer (*=) Right outer (=*)
SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column *= table2.column
SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column *= table2.column
SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column =* table2.column
SELECT table1.column, table2.column
FROM table1, table2
WHERE table1.column =* table2.column
Outer JoinsOuter JoinsOuter JoinsOuter JoinsEMP EMP DEPT DEPT
No employee in theNo employee in theOPERATIONS departmentOPERATIONS department
ENAME DEPTNO----- ------KING 10BLAKE 30CLARK 10JONES 20...
DEPTNO DNAME------ ----------10 ACCOUNTING20 RESEARCH...40 OPERATIONS
Using Outer JoinsUsing Outer JoinsUsing Outer JoinsUsing Outer JoinsSELECT e.ename, d.deptno, d.dname
FROM emp e LEFT OUTER JOIN dept d
ON e.deptno = d.deptno
ORDER BY e.deptno
ENAME DEPTNO DNAME---------- --------- -------------KING 10 ACCOUNTINGCLARK 10 ACCOUNTING... 40 OPERATIONS15 rows selected.
Example 1Example 1
SELECT e.ename, d.deptno, d.dnameFROM emp e LEFT OUTER JOIN dept d
ON e.deptno = d.deptnoORDER BY d.deptno
— OR—SELECT e.ename, d.deptno, d.dnameFROM emp e, dept dWHERE e.deptno *= d.deptnoORDER BY d.deptno
SELECT e.ename, d.deptno, d.dname
FROM emp e RIGHT OUTER JOIN dept d
ON e.deptno = d.deptno
ORDER BY d.deptno
— OR—
SELECT e.ename, d.deptno, d.dname
FROM emp e, dept d
WHERE e.deptno =* d.deptno
ORDER BY d.deptno
Example 2Example 2
Full Outer JoinFull 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 JoinFull Outer Join
SELECT e.ename, d.deptno, d.dname
FROM emp e FULL OUTER JOIN dept d
ON e.deptno = d.deptno
ORDER BY d.deptno
Self JoinsSelf JoinsSelf JoinsSelf JoinsEMP (WORKER)EMP (WORKER) EMP (MANAGER)EMP (MANAGER)
““MGR in the WORKER table is equal to EMPNO in the MGR in the WORKER table is equal to EMPNO in the MANAGER table”MANAGER table”
EMPNO ENAME MGR----- ------ ---- 7839 KING 7698 BLAKE 7839 7782 CLARK 7839 7566 JONES 7839 7654 MARTIN 7698 7499 ALLEN 7698
EMPNO ENAME----- --------
7839 KING 7839 KING 7839 KING 7698 BLAKE 7698 BLAKE
Self JoinSelf 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.
ExampleExample
SELECT worker.ename + ' works for ' + manager.ename
FROM emp worker, emp manager
WHERE worker.mgr = manager.empno
Joining a Table to ItselfJoining a Table to ItselfJoining a Table to ItselfJoining a Table to Itself
-------------------------------BLAKE works for KINGCLARK works for KINGJONES works for KINGMARTIN works for BLAKE...13 rows selected.
-------------------------------BLAKE works for KINGCLARK works for KINGJONES works for KINGMARTIN works for BLAKE...13 rows selected.
SELECT worker.ename + ' works for ' + manager.enameFROM emp worker INNER JOIN emp manager
ON worker.mgr = manager.empno
Qualifying Ambiguous Qualifying Ambiguous Column NamesColumn Names
Qualifying Ambiguous Qualifying Ambiguous Column NamesColumn 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 ConditionsAdditional Search ConditionsUsing the AND Operator Using the AND Operator
Additional Search ConditionsAdditional Search ConditionsUsing the AND Operator Using the AND Operator
EMP EMP DEPT 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 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON
4 rows selected.
Using Table AliasesUsing Table AliasesUsing Table AliasesUsing Table AliasesSimplify queries by 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 Joining More Than Two TablesTables
Joining More Than Two Joining More Than Two TablesTables
NAME CUSTID----------- ------JOCKSPORTS 100TKB SPORT SHOP 101VOLLYRITE 102JUST TENNIS 103K+T SPORTS 105SHAPE UP 106WOMENS SPORTS 107... ...9 rows selected.
NAME CUSTID----------- ------JOCKSPORTS 100TKB SPORT SHOP 101VOLLYRITE 102JUST TENNIS 103K+T SPORTS 105SHAPE UP 106WOMENS SPORTS 107... ...9 rows selected.
CUSTOMER 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 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 ITEM
SummarySummarySummarySummary
EquijoinEquijoin Non-equijoinNon-equijoin Outer joinOuter join Self joinSelf join
SELECT table1.column, table2.columnFROM table1, table2WHERE table1.column1 = table2.column2;
SELECT table1.column, table2.columnFROM table1, table2WHERE table1.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
SELECT top 3 deptno, ename
FROM emp
Top nTop nTop nTop n
SubqueriesSubqueriesSubqueriesSubqueries
ObjectivesObjectivesObjectivesObjectives
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 Using a Subquery to Solve a Problemto Solve a ProblemUsing a Subquery Using a Subquery to Solve a Problemto Solve a Problem
“Who has a salary greater than Jones’?” “Who has a salary greater than Jones’?”
“Which employees have a salary greater than Jones’ salary?”
Main Query
??
“What is Jones’ salary?”??
Subquery
SubqueriesSubqueriesSubqueriesSubqueries
– 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).
SELECT select_listFROM tableWHERE expr operator
(SELECT select_list FROM table)
2975
SELECT ename FROM emp WHERE sal > (SELECT sal FROM emp WHERE empno=7566)
Using a SubqueryUsing a SubqueryUsing a SubqueryUsing a Subquery
ENAME----------KINGFORDSCOTT
ENAME----------KINGFORDSCOTT
Guidelines for Using Guidelines for Using SubqueriesSubqueries
Guidelines for Using Guidelines for Using SubqueriesSubqueries
– 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 SubqueriesTypes of SubqueriesTypes of SubqueriesTypes of Subqueries– Single-row subquery– Single-row subquery
Main query
Subquery returnsreturns
CLERKCLERK
• Multiple-row subquery• Multiple-row subquery
CLERKCLERKMANAGERMANAGER
Main query
Subquery returnsreturns
• Multiple-column subquery• Multiple-column subquery
CLERK 7900CLERK 7900MANAGER 7698MANAGER 7698
Main query
Subquery returnsreturns
Single-Row SubqueriesSingle-Row SubqueriesSingle-Row SubqueriesSingle-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 Executing Single-Row SubqueriesSubqueries
Executing Single-Row Executing Single-Row SubqueriesSubqueries
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 FROM emp WHERE empno = 7876)
Using Group Functions Using Group Functions in a Subqueryin a Subquery
Using Group Functions Using Group Functions in a Subqueryin a Subquery
800
ENAME JOB SAL---------- --------- ---------SMITH CLERK 800
ENAME JOB SAL---------- --------- ---------SMITH CLERK 800
SELECT ename, job, sal FROM emp WHERE sal = (SELECT MIN(sal) FROM emp)
HAVING Clause with HAVING Clause with SubqueriesSubqueries
HAVING Clause with HAVING Clause with SubqueriesSubqueries
– 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
SELECT deptno, MIN(sal) FROM emp GROUP BY deptno HAVING MIN(sal) > (SELECT MIN(sal) FROM emp WHERE deptno = 20)
What Is Wrong What Is Wrong with This Statement?with This Statement?
What Is Wrong What Is Wrong with This Statement?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
Single-row operator with
multiple-row subquery
multiple-row subquery
Will This Statement Work?Will This Statement Work?Will This Statement Work?Will This Statement Work?
no rows selectedno rows selected
Subquery returns no values
Subquery returns no values
SELECT ename, job FROM emp WHERE job = (SELECT job FROM emp WHERE ename='SMYTHE')
Multiple-Row SubqueriesMultiple-Row SubqueriesMultiple-Row SubqueriesMultiple-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 Using ANY Operator in Multiple-Row Subqueriesin Multiple-Row Subqueries
Using ANY Operator Using ANY Operator in Multiple-Row Subqueriesin Multiple-Row Subqueries
9508001100
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 (SELECT sal FROM emp WHERE job = 'CLERK') AND job <> 'CLERK'
Using ALL Operator Using ALL Operator in Multiple-Row Subqueriesin Multiple-Row Subqueries
Using ALL Operator Using ALL Operator in Multiple-Row Subqueriesin 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 (SELECT avg(sal) FROM emp GROUP BY deptno)
SubquerySubquerySubquerySubquery
SELECT ordid, prodid, qty FROM item WHERE prodid IN (SELECT prodid FROM item WHERE ordid = 605) AND qty IN (SELECT qty FROM item WHERE ordid = 605) AND ordid <> 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.
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.
SubquerySubquerySubquerySubquery
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.
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 SubqueryNull Values in a SubqueryNull Values in a SubqueryNull Values in a Subquery
SELECT employee.ename FROM emp employee WHERE employee.empno NOT IN (SELECT manager.mgr FROM emp manager)no rows selected.no rows selected.
SELECT employee.ename FROM emp employee WHERE employee.empno NOT IN (SELECT ISNULL(manager.mgr,0) FROM emp manager)
Using a Subquery Using a Subquery in the FROM Clausein the FROM ClauseUsing a Subquery Using a Subquery
in the FROM Clausein the FROM Clause
ENAME SAL DEPTNO SALAVG---------- --------- --------- ----------KING 5000 10 2916.6667JONES 2975 20 2175SCOTT 3000 20 2175...6 rows selected.
ENAME SAL DEPTNO SALAVG---------- --------- --------- ----------KING 5000 10 2916.6667JONES 2975 20 2175SCOTT 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
Some Data TypesSome Data Types
IntegersIntegers
bigintInteger (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).
smallintInteger data from 2^15 (-32,768) through 2^15 - 1
(32,767).tinyint
Integer data from 0 through 255.
bitbit
Integer data with either a 1 or 0 value.
decimal and numericdecimal and numericdecimal
Fixed precision and scale numeric data from -10^38 +1 through 10^38 –1.
numeric
Functionally equivalent to decimal.
money and smallmoney 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.
datetime and smalldatetime datetime and smalldatetime
datetimeDate 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 StringsCharacter Strings
charFixed-length non-Unicode character data with a
maximum length of 8,000 characters.
varcharVariable-length non-Unicode data with a maximum of
8,000 characters.
textVariable-length non-Unicode data with a maximum
length of 2^31 - 1 (2,147,483,647) characters.