More Related Content
Similar to Oracle sql & plsql (20)
Oracle sql & plsql
- 2. Oracle SQL & PL/SQL
Huiyun Mao
Yolanda.mao@oracle.com
Copyright © 2004, Oracle. All rights reserved.
- 4. SQL Statements
SELECT Data retrieval language (DRL)
INSERT
UPDATE Data manipulation language (DML)
DELETE
CREATE
ALTER
DROP Data definition language (DDL)
RENAME
TRUNCATE
COMMIT
ROLLBACK Transaction control
SAVEPOINT
GRANT
Data control language (DCL)
REVOKE
Copyright © 2004, Oracle. All rights reserved.
- 5. Tables Used in the Course
Three main tables are used in this course:
Three main tables are used in this course:
–
– EMP table
EMP table
–
– DEPT table
DEPT table
Copyright © 2004, Oracle. All rights reserved.
- 6. The EMP Table
EMP
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
--------- ---------- --------- --------- --------- --------- --------- ---------
7839 KING PRESIDENT 17-NOV-81 5000 10
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 1500 10
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7900 JAMES CLERK 7698 03-DEC-81 950 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7369 SMITH CLERK 7902 17-DEC-80 800 20
7788 SCOTT ANALYST 7566 09-DEC-82 3000 20
7876 ADAMS CLERK 7788 12-JAN-83 1100 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10
Primary key Foreign key Foreign key
Copyright © 2004, Oracle. All rights reserved.
- 7. DEPT Tables
DEPT
DEPTNO DNAME LOC
--------- -------------- ----------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
Primary key
Copyright © 2004, Oracle. All rights reserved.
- 8. Writing Basic
SQL Statements
Copyright © 2004, Oracle. All rights reserved.
- 9. Capabilities of SQL SELECT
Statements
Restriction Projection
Table 1 Table 1
Join
Table 1 Table 2
Copyright © 2004, Oracle. All rights reserved.
- 10. Basic SELECT Statement
SELECT [DISTINCT] {*, column [alias],...}
FROM table
[WHERE condition(s)]
[GROUP BY group_by_expression]
[ORDER BY column];
–
– SELECT identifies the columns to be displayed.
SELECT identifies the columns to be displayed.
–
– FROM identifies the table that contains the columns.
FROM identifies the table that contains the columns.
Copyright © 2004, Oracle. All rights reserved.
- 11. Writing SQL Statements
–
– SQL statements are not case sensitive.
SQL statements are not case sensitive.
–
– SQL statements can be on one or
SQL statements can be on one or
more lines.
more lines.
–
– Keywords cannot be abbreviated or split across lines.
Keywords cannot be abbreviated or split across lines.
–
– Clauses are usually placed on
Clauses are usually placed on
separate lines.
separate lines.
–
– Tabs and indents are used to enhance readability.
Tabs and indents are used to enhance readability.
Copyright © 2004, Oracle. All rights reserved.
- 12. Retrieving All Columns
from a Table
DEPT Retrieve all
DEPTNO DNAME LOC
columns from the
10 ACCOUNTING NEW YORK DEPT table
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
DEPT
DEPTNO DNAME LOC
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
All columns are displayed
Copyright © 2004, Oracle. All rights reserved.
- 13. Selecting All Columns
SQL> SELECT *
2 FROM dept;
DEPTNO DNAME LOC
--------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
Copyright © 2004, Oracle. All rights reserved.
- 14. Creating a Projection on a Table
DEPT
DEPTNO DNAME LOC Retrieve DEPTNO
and LOC columns
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
from the DEPT
30 SALES CHICAGO table
40 OPERATIONS BOSTON
DEPT
DEPTNO LOC
10 NEW YORK
20 DALLAS
30 CHICAGO
40 BOSTON
Only two columns are displayed
Copyright © 2004, Oracle. All rights reserved.
- 15. Selecting Specific Columns
SQL> SELECT deptno, loc
2 FROM dept;
DEPTNO LOC
--------- -------------
10 NEW YORK
20 DALLAS
30 CHICAGO
40 BOSTON
Copyright © 2004, Oracle. All rights reserved.
- 16. Default Column Justification
Character Date Number
left justified left justified right justified
EMP
ENAME HIREDATE SAL
---------- --------- ---------
KING 17-NOV-81 5000
BLAKE 01-MAY-81 2850
CLARK 09-JUN-81 2450
JONES 02-APR-81 2975
MARTIN 28-SEP-81 1250
ALLEN 20-FEB-81 1600
...
14 rows selected.
Copyright © 2004, Oracle. All rights reserved.
- 17. Arithmetic Expressions
Create expressions on NUMBER and DATE data
Create expressions on NUMBER and DATE data
types by using arithmetic operators.
types by using arithmetic operators.
Operator Description
+ Add
- Subtract
* Multiply
/ Divide
Copyright © 2004, Oracle. All rights reserved.
- 18. Using Arithmetic Operators
SQL> SELECT ename, sal, sal+300
2 FROM emp;
ENAME SAL SAL+300
---------- --------- ---------
KING 5000 5300
BLAKE 2850 3150
CLARK 2450 2750
JONES 2975 3275
MARTIN 1250 1550
ALLEN 1600 1900
...
14 rows selected.
Copyright © 2004, Oracle. All rights reserved.
- 19. Using Arithmetic Operators on
Multiple Columns
SQL> SELECT grade, hisal-losal
2 FROM salgrade;
GRADE HISAL-LOSAL
--------- -----------
1 500
2 199
3 599
4 999
5 6998
Copyright © 2004, Oracle. All rights reserved.
- 20. Operator Precedence
/ + _
*
–
– Multiplication and division take priority over addition
Multiplication and division take priority over addition
and subtraction.
and subtraction.
–
– Operators of the same priority are evaluated from left to
Operators of the same priority are evaluated from left to
right.
right.
–
– Parentheses are used to force prioritized evaluation
Parentheses are used to force prioritized evaluation
and to clarify statements.
and to clarify statements.
Copyright © 2004, Oracle. All rights reserved.
- 21. Operator Precedence
SQL> SELECT ename, sal, 12*sal+100
2 FROM emp;
ENAME SAL 12*SAL+100
---------- --------- ----------
KING 5000 60100
BLAKE 2850 34300
CLARK 2450 29500
JONES 2975 35800
MARTIN 1250 15100
ALLEN 1600 19300
...
14 rows selected.
Copyright © 2004, Oracle. All rights reserved.
- 22. Using Parentheses
SQL> SELECT ename, sal, 12*(sal+100)
2 FROM emp;
ENAME SAL 12*(SAL+100)
---------- --------- -----------
KING 5000 61200
BLAKE 2850 35400
CLARK 2450 30600
JONES 2975 36900
MARTIN 1250 16200
...
14 rows selected.
Copyright © 2004, Oracle. All rights reserved.
- 23. Defining a Column Alias
–
– Renames a column heading
Renames a column heading
–
– Is useful with calculations
Is useful with calculations
–
– Immediately follows column name; optional AS
Immediately follows column name; optional AS
keyword between column name and alias
keyword between column name and alias
–
– Requires double quotation marks if it is case sensitive
Requires double quotation marks if it is case sensitive
or contains spaces or special characters
or contains spaces or special characters
Copyright © 2004, Oracle. All rights reserved.
- 24. Using Column Aliases
SQL> SELECT ename AS name, sal salary
2 FROM emp;
NAME SALARY
------------- ---------
KING 5000
BLAKE 2850
CLARK 2450
JONES 2975
...
14 rows selected.
Copyright © 2004, Oracle. All rights reserved.
- 25. Using Column Aliases
SQL> SELECT ename "Name",
2 sal*12 "Annual Salary"
3 FROM emp;
Name Annual Salary
------------- -------------
KING 60000
BLAKE 34200
CLARK 29400
...
14 rows selected.
Copyright © 2004, Oracle. All rights reserved.
- 26. Concatenation Operator
–
– Concatenates columns or character strings to other
Concatenates columns or character strings to other
columns
columns
–
– Is represented by two vertical bars ||
Is represented by two vertical bars ||
–
– Creates a result column that is a character expression
Creates a result column that is a character expression
Copyright © 2004, Oracle. All rights reserved.
- 27. Using the Concatenation Operator
SQL> SELECT ename||job AS "Employees"
2 FROM emp;
Employees
-------------------
KINGPRESIDENT
BLAKEMANAGER
CLARKMANAGER
JONESMANAGER
MARTINSALESMAN
ALLENSALESMAN
...
14 rows selected.
Copyright © 2004, Oracle. All rights reserved.
- 28. Literals
–
– A literal is a constant value of character, expression, or
A literal is a constant value of character, expression, or
number that can be included in the SELECT list.
number that can be included in the SELECT list.
–
– Date and character literal values must be enclosed in
Date and character literal values must be enclosed in
single quotation marks.
single quotation marks.
–
– Each character string is output once for each row
Each character string is output once for each row
returned.
returned.
Copyright © 2004, Oracle. All rights reserved.
- 29. Using Literal Character Strings
SQL> SELECT ename||' is a '||job AS
2 "Employee Details"
3 FROM emp;
Employee Details
-------------------------
KING is a PRESIDENT
BLAKE is a MANAGER
CLARK is a MANAGER
JONES is a MANAGER
MARTIN is a SALESMAN
...
14 rows selected.
Copyright © 2004, Oracle. All rights reserved.
- 30. Duplicate Rows
The default display of queries is all rows, including
The default display of queries is all rows, including
duplicate rows.
duplicate rows.
SQL> SELECT deptno
2 FROM emp;
DEPTNO
---------
10
30
10
20
..
14 rows selected.
Copyright © 2004, Oracle. All rights reserved.
- 31. Eliminating Duplicate Rows
Eliminate duplicate rows by using the DISTINCT
Eliminate duplicate rows by using the DISTINCT
keyword in the SELECT clause.
keyword in the SELECT clause.
SQL> SELECT DISTINCT deptno
2 FROM emp;
DEPTNO
---------
10
20
30
Copyright © 2004, Oracle. All rights reserved.
- 33. Limiting Rows by Using a Restriction
EMP
EMPNO ENAME JOB ... DEPTNO
Retrieve all
7839 KING PRESIDENT 10 employees
7698 BLAKE MANAGER 30 in department 10
7782 CLARK MANAGER 10
7566 JONES MANAGER 20
...
EMP
EMPNO ENAME JOB ... DEPTNO
7839 KING PRESIDENT 10
7782 CLARK MANAGER 10
7934 MILLER CLERK 10
Copyright © 2004, Oracle. All rights reserved.
- 34. Using the WHERE Clause
SQL> SELECT ename, job, deptno
2 FROM emp
3 WHERE deptno=10;
ENAME JOB DEPTNO
---------- --------- ---------
KING PRESIDENT 10
CLARK MANAGER 10
MILLER CLERK 10
Copyright © 2004, Oracle. All rights reserved.
- 35. Character Strings and Dates
–
– Character strings and date values are enclosed in
Character strings and date values are enclosed in
single quotation marks.
single quotation marks.
–
– Character values are case sensitive and date values
Character values are case sensitive and date values
are format sensitive.
are format sensitive.
–
– Default date format is DD-MON-YY.
Default date format is DD-MON-YY.
SQL> SELECT ename, job, deptno, hiredate
2 FROM emp
3 WHERE ename = 'JAMES';
Copyright © 2004, Oracle. All rights reserved.
- 36. Comparison Operators
Operator Meaning
= Equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
<> Not equal to
Copyright © 2004, Oracle. All rights reserved.
- 37. Using the Comparison Operators
with Another Column
SQL> SELECT ename, sal, comm
2 FROM emp
3 WHERE sal<=comm;
ENAME SAL COMM
---------- --------- ---------
MARTIN 1250 1400
Copyright © 2004, Oracle. All rights reserved.
- 38. Using the Comparison Operators
with Characters
SQL> SELECT ename, mgr
2 FROM emp
3 WHERE ename='SMITH';
ENAME MGR
---------- ---------
SMITH 7902
Copyright © 2004, Oracle. All rights reserved.
- 39. Other SQL Comparison Operators
Operator Meaning
BETWEEN Between two values (inclusive)
...AND...
IN(list) Match any of a list of values
LIKE Match a character pattern
IS NULL Is a null value
Copyright © 2004, Oracle. All rights reserved.
- 40. Using the BETWEEN Operator
Use the BETWEEN operator to display rows based on
Use the BETWEEN operator to display rows based on
a range of values.
a range of values.
SQL> SELECT ename, sal
2 FROM emp
3 WHERE sal BETWEEN 1000 AND 1500;
ENAME SAL
---------- --------- Lower Higher
MARTIN 1250 limit limit
TURNER 1500
WARD 1250
ADAMS 1100
MILLER 1300
Copyright © 2004, Oracle. All rights reserved.
- 41. Using the IN Operator
Use the IN operator to test for values in a list.
Use the IN operator to test for values in a list.
SQL> SELECT empno, ename, sal, mgr
2 FROM emp
3 WHERE mgr IN (7902, 7566, 7788);
EMPNO ENAME SAL MGR
--------- ---------- --------- ---------
7902 FORD 3000 7566
7369 SMITH 800 7902
7788 SCOTT 3000 7566
7876 ADAMS 1100 7788
Copyright © 2004, Oracle. All rights reserved.
- 42. Using the IN Operator with Strings
Use the IN operator to test for values in a list of
Use the IN operator to test for values in a list of
strings.
strings.
SQL> SELECT ename, deptno, hiredate
2 FROM emp
3 WHERE ename IN ('BLAKE','MARTIN');
ENAME DEPTNO HIREDATE
---------- --------- ---------
BLAKE 30 01-MAY-81
MARTIN 30 28-SEP-81
Copyright © 2004, Oracle. All rights reserved.
- 43. Using the LIKE Operator
–
– Use the LIKE operator to perform wildcard searches of
Use the LIKE operator to perform wildcard searches of
valid search string values.
valid search string values.
–
– Search conditions can contain either literal characters
Search conditions can contain either literal characters
or numbers.
or numbers.
% denotes zero or many characters
% denotes zero or many characters
_ denotes one character
_ denotes one character
SQL> SELECT ename
2 FROM emp
3 WHERE ename LIKE 'S%';
Copyright © 2004, Oracle. All rights reserved.
- 44. Using the LIKE Operator
• You can combine pattern matching
• You can combine pattern matching
characters.
characters.
SQL> SELECT ename
2 FROM emp
3 WHERE ename LIKE '_A%';
ENAME
----------
MARTIN
JAMES
WARD
• Use the ESCAPE identifier to search for
• Use the ESCAPE identifier to search for
% or _.
% or _.
Copyright © 2004, Oracle. All rights reserved.
- 45. Using the IS NULL Operator
Test for null values with the IS NULL operator.
Test for null values with the IS NULL operator.
SQL> SELECT ename, mgr
2 FROM emp
3 WHERE mgr IS NULL;
ENAME MGR
---------- ---------
KING
Copyright © 2004, Oracle. All rights reserved.
- 46. Logical Operators
Operator Meaning
AND Returns TRUE if both component
conditions are TRUE
OR Returns TRUE if either component
condition is TRUE
NOT Returns TRUE if the following
condition is FALSE
Copyright © 2004, Oracle. All rights reserved.
- 47. Using the AND Operator
AND requires both conditions to be TRUE.
AND requires both conditions to be TRUE.
SQL> SELECT empno, ename, job, sal
2 FROM emp
3 WHERE sal>=1100
4 AND job='CLERK';
EMPNO ENAME JOB SAL
--------- ---------- --------- ---------
7876 ADAMS CLERK 1100
7934 MILLER CLERK 1300
Copyright © 2004, Oracle. All rights reserved.
- 48. Using the AND Operator
AND requires both conditions to be TRUE.
AND requires both conditions to be TRUE.
SQL> SELECT ename, mgr, sal,deptno
2 FROM emp
3 WHERE sal>1000
4 AND deptno = 10;
ENAME MGR SAL DEPTNO
---------- --------- --------- ---------
KING 5000 10
CLARK 7839 2450 10
MILLER 7782 1300 10
Copyright © 2004, Oracle. All rights reserved.
- 49. Using the OR Operator
OR requires either condition to be TRUE.
OR requires either condition to be TRUE.
SQL> SELECT empno, ename, job, sal
2 FROM emp
3 WHERE sal>=2000
4 OR job='CLERK';
EMPNO ENAME JOB SAL
--------- ---------- --------- ---------
7839 KING PRESIDENT 5000
7698 BLAKE MANAGER 2850
7782 CLARK MANAGER 2450
7566 JONES MANAGER 2975
7900 JAMES CLERK 950
7902 FORD ANALYST 3000
...
10 rows selected.
Copyright © 2004, Oracle. All rights reserved.
- 50. Using the OR Operator
OR requires either condition to be TRUE.
OR requires either condition to be TRUE.
SQL> SELECT ename, deptno, mgr
2 FROM emp
3 WHERE deptno = 10
4 OR mgr = 7839;
ENAME DEPTNO MGR
---------- -------- ---------
KING 10
BLAKE 30 7839
CLARK 10 7839
JONES 20 7839
MILLER 10 7782
Copyright © 2004, Oracle. All rights reserved.
- 51. Using the NOT Operator
SQL> SELECT ename, job
2 FROM emp
3 WHERE job NOT IN ('CLERK','MANAGER','ANALYST');
ENAME JOB
---------- ---------
KING PRESIDENT
MARTIN SALESMAN
ALLEN SALESMAN
TURNER SALESMAN
WARD SALESMAN
Copyright © 2004, Oracle. All rights reserved.
- 52. Using the NOT Operator
SQL> SELECT empno,ename,deptno,mgr
2 FROM emp
3 WHERE mgr NOT LIKE '78%';
EMPNO ENAME DEPTNO MGR
--------- ---------- --------- ---------
7654 MARTIN 30 7698
7499 ALLEN 30 7698
...
...
7902 FORD 20 7566
7369 SMITH 20 7902
...
10 rows selected.
Copyright © 2004, Oracle. All rights reserved.
- 53. Using the NOT Operator
SQL> SELECT empno, sal, mgr
2 FROM emp
3 WHERE sal NOT BETWEEN 1000 AND 1500;
EMPNO SAL MGR
--------- --------- ---------
7839 5000
7698 2850 7839
7782 2450 7839
7566 2975 7839
7499 1600 7698
7900 950 7698
7902 3000 7566
7369 800 7902
7788 3000 7566
9 rows selected.
Copyright © 2004, Oracle. All rights reserved.
- 54. Using the NOT Operator
SQL> SELECT ename, sal AS "Salary Before Commission",
2 comm
3 FROM emp
4 WHERE comm IS NOT NULL;
ENAME Salary Before Commission COMM
---------- ------------------------ ---------
MARTIN 1250 1400
ALLEN 1600 300
TURNER 1500 0
WARD 1250 500
Copyright © 2004, Oracle. All rights reserved.
- 55. Rules of Precedence
Order Evaluated Operator
1 All comparison
operators
2 NOT
3 AND
4 OR
Use parentheses to override rules of precedence.
Use parentheses to override rules of precedence.
Copyright © 2004, Oracle. All rights reserved.
- 56. Rules of Precedence
SQL> SELECT ename, job, sal
2 FROM emp
3 WHERE job='SALESMAN'
4 OR job='PRESIDENT'
5 AND sal>1500;
ENAME JOB SAL
---------- ------- ---------
KING PRESIDENT 5000
MARTIN SALESMAN 1250
ALLEN SALESMAN 1600
TURNER SALESMAN 1500
WARD SALESMAN 1250
Copyright © 2004, Oracle. All rights reserved.
- 57. Rules of Precedence
Use parentheses to force priority.
Use parentheses to force priority.
SQL> SELECT ename, job, sal
2 FROM emp
3 WHERE (job='SALESMAN'
4 OR job='PRESIDENT')
5 AND sal>1500;
ENAME JOB SAL
---------- --------- ---------
KING PRESIDENT 5000
ALLEN SALESMAN 1600
Copyright © 2004, Oracle. All rights reserved.
- 58. ORDER BY Clause
–
– Sort rows with the ORDER BY clause:
Sort rows with the ORDER BY clause:
ASC: ascending order, default
ASC: ascending order, default
DESC: descending order
DESC: descending order
–
– The ORDER BY clause comes last in the SELECT
The ORDER BY clause comes last in the SELECT
statement.
statement.
SQL> SELECT ename, job, deptno
2 FROM emp
3 ORDER BY deptno;
ENAME JOB DEPTNO
---------- --------- ---------
KING PRESIDENT 10
CLARK MANAGER 10
...
JONES MANAGER 20
SCOTT ANALYST 20
...
14 rows selected.
Copyright © 2004, Oracle. All rights reserved.
- 59. Sorting in Descending Order
SQL> SELECT ename, job, deptno, sal
2 FROM emp
3 ORDER BY sal DESC;
ENAME JOB DEPTNO SAL
---------- --------- --------- ---------
KING PRESIDENT 10 5000
FORD ANALYST 20 3000
SCOTT ANALYST 20 3000
JONES MANAGER 20 2975
BLAKE MANAGER 30 2850
CLARK MANAGER 10 2450
ALLEN SALESMAN 30 1600
...
14 rows selected.
Copyright © 2004, Oracle. All rights reserved.
- 60. Sorting by Column Alias
SQL> SELECT empno, ename, sal*12 annsal
2 FROM emp
3 ORDER BY annsal;
EMPNO ENAME ANNSAL
--------- ---------- ---------
7369 SMITH 9600
7900 JAMES 11400
7876 ADAMS 13200
7654 MARTIN 15000
7521 WARD 15000
7934 MILLER 15600
7844 TURNER 18000
...
14 rows selected.
Copyright © 2004, Oracle. All rights reserved.
- 61. Sorting by Multiple Columns
The order of an ORDER BY list is the order of the
The order of an ORDER BY list is the order of the
sort.
sort.
SQL> SELECT ename, deptno, sal
2 FROM emp
3 ORDER BY deptno, sal DESC;
ENAME DEPTNO SAL
---------- --------- ---------
KING 10 5000
CLARK 10 2450
MILLER 10 1300
FORD 20 3000
...
14 rows selected.
Copyright © 2004, Oracle. All rights reserved.
- 62. Sorting by a Column Not in the
SELECT List
SQL> SELECT ename, deptno
2 FROM emp
3 ORDER BY sal;
ENAME DEPTNO
---------- ---------
SMITH 20
JAMES 30
ADAMS 20
MARTIN 30
WARD 30
MILLER 10
...
14 rows selected.
Copyright © 2004, Oracle. All rights reserved.
- 64. How a Function Works
Input Function Output
Performs
operation
Copyright © 2004, Oracle. All rights reserved.
- 65. Two Types of SQL Functions
Functions
Single-row Multiple-row
functions functions
Copyright © 2004, Oracle. All rights reserved.
- 66. Single-Row Functions
–
– Manipulate data items
Manipulate data items
–
– Accept arguments and return one value
Accept arguments and return one value
–
– Act on each row returned
Act on each row returned
–
– Return one result per row
Return one result per row
–
– Can modify the data type
Can modify the data type
–
– Can be nested
Can be nested
Copyright © 2004, Oracle. All rights reserved.
- 67. Single-Row Functions
Character Number
Single-row
functions
Conversion Date
Copyright © 2004, Oracle. All rights reserved.
- 68. Character Functions
Character
functions
Case conversion Character manipulation
functions functions
LOWER
UPPER
INITCAP
Copyright © 2004, Oracle. All rights reserved.
- 69. Case Conversion Functions
Convert the case for character strings
Convert the case for character strings
Function Result
LOWER('SQL Course') sql course
UPPER('SQL Course') SQL COURSE
INITCAP('SQL Course') Sql Course
Copyright © 2004, Oracle. All rights reserved.
- 70. Using Case Conversion Functions
Display the employee number, name, and department
Display the employee number, name, and department
number for employee Blake.
number for employee Blake.
SQL> SELECT empno, ename, deptno
2 FROM emp
3 WHERE ename = 'blake';
no rows selected
SQL> SELECT empno, ename, deptno
2 FROM emp
3 WHERE ename = UPPER('blake');
EMPNO ENAME DEPTNO
--------- ---------- ---------
7698 BLAKE 30
Copyright © 2004, Oracle. All rights reserved.
- 71. Using Case Conversion Functions
Display the employee name for all employees with an
Display the employee name for all employees with an
initial capital.
initial capital.
SQL> SELECT INITCAP(ename) as EMPLOYEE
2 FROM emp;
EMPLOYEE
----------
King
Blake
Clark
Jones
Martin
...
14 rows selected.
Copyright © 2004, Oracle. All rights reserved.
- 72. Number Functions
–
– ROUND: Rounds value to specified decimal
ROUND: Rounds value to specified decimal
ROUND(45.926, 2)
ROUND(45.926, 2)
45.93
45.93
–
– TRUNC: Truncates value to specified decimal
TRUNC: Truncates value to specified decimal
TRUNC(45.926, 2)
TRUNC(45.926, 2)
45.92
45.92
–
– MOD: Returns remainder of division
MOD: Returns remainder of division
MOD(1600, 300)
MOD(1600, 300)
100
100
Copyright © 2004, Oracle. All rights reserved.
- 73. Defining a Null Value
–
– A null is a value that is unavailable, unassigned,
A null is a value that is unavailable, unassigned,
unknown, or inapplicable.
unknown, or inapplicable.
–
– A null is not the same as zero or a blank space.
A null is not the same as zero or a blank space.
SQL> SELECT ename, job, comm
2 FROM emp;
ENAME JOB COMM
---------- --------- ---------
KING PRESIDENT
BLAKE MANAGER
...
TURNER SALESMAN 0
...
14 rows selected.
Copyright © 2004, Oracle. All rights reserved.
- 74. Null Values in Arithmetic
Expressions
Arithmetic expressions that contain a null value
Arithmetic expressions that contain a null value
evaluate to null.
evaluate to null.
SQL> SELECT ename NAME, 12*sal+comm
2 FROM emp;
NAME 12*SAL+COMM
---------- -----------
KING
BLAKE
CLARK
JONES
MARTIN 16400
...
14 rows selected.
Copyright © 2004, Oracle. All rights reserved.
- 75. Using the NVL Function
NVL (expr1, expr2)
Use the NVL function to force a value where a null
Use the NVL function to force a value where a null
would otherwise appear:
would otherwise appear:
–
– NVL can be used with date, character, and number
NVL can be used with date, character, and number
data types.
data types.
–
– Data types must match. For example:
Data types must match. For example:
NVL(comm,0)
NVL(comm,0)
NVL(hiredate,'01-JAN-97')
NVL(hiredate,'01-JAN-97')
NVL(job,'no job yet')
NVL(job,'no job yet'
yet')
Copyright © 2004, Oracle. All rights reserved.
- 76. Using the NVL Function to Handle
Null Values
SQL> SELECT ename, job, sal * 12 + NVL(comm,0)
2 FROM emp;
ENAME JOB SAL*12+NVL(COMM,0)
---------- --------- ------------------
KING PRESIDENT 60000
BLAKE MANAGER 34200
CLARK MANAGER 29400
JONES MANAGER 35700
MARTIN SALESMAN 16400
ALLEN SALESMAN 19500
TURNER SALESMAN 18000
...
14 rows selected.
Copyright © 2004, Oracle. All rights reserved.
- 78. Single-Row Functions
Character Number
Single-row
functions
Conversion Date
Copyright © 2004, Oracle. All rights reserved.
- 79. Working with Dates
–
– Oracle stores dates in an internal 7 byte numeric format:
Oracle stores dates in an internal 7 byte numeric format:
century, year, month, day, hours, minutes, seconds.
century, year, month, day, hours, minutes, seconds.
–
– The default date format is DD-MON-YY.
The default date format is DD-MON-YY.
Copyright © 2004, Oracle. All rights reserved.
- 80. SYSDATE
–
– Use SYSDATE to display the current date and time.
Use SYSDATE to display the current date and time.
–
– DUAL is a one-column, one-row table that is used as a
DUAL is a one-column, one-row table that is used as a
dummy table.
dummy table.
SQL> SELECT SYSDATE
2 FROM DUAL;
SYSDATE
---------
26-JAN-98
Copyright © 2004, Oracle. All rights reserved.
- 81. Default Date Formats
Columns that are defined as DATE are
Columns that are defined as DATE are
displayed as DD-MON-YY by default.
displayed as DD-MON-YY by default.
SQL> SELECT ename, hiredate
2 FROM emp
3 WHERE ename='SMITH';
ENAME HIREDATE
---------- ---------
SMITH 17-DEC-80
Copyright © 2004, Oracle. All rights reserved.
- 82. Arithmetic with Dates
–
– Add or subtract a number to or from a date to obtain a date
Add or subtract a number to or from a date to obtain a date
value
value
–
– Subtract two dates to find the number of days between
Subtract two dates to find the number of days between
those dates
those dates
Copyright © 2004, Oracle. All rights reserved.
- 83. Using Arithmetic Operators
with Dates
SQL> SELECT ename, hiredate, hiredate+30 "NEW DATE"
2 FROM emp
3 WHERE ename='SMITH';
ENAME HIREDATE NEW DATE
---------- --------- ---------
SMITH 17-DEC-80 16-JAN-81
Copyright © 2004, Oracle. All rights reserved.
- 84. Using SYSDATE in Calculations
Determine for how many weeks employees have
Determine for how many weeks employees have
worked
worked
SQL> SELECT ename, (SYSDATE-hiredate)/7
2 "WEEKS AT WORK"
3 FROM emp
4 WHERE deptno=10;
ENAME WEEKS AT WORK
---------- -------------
KING 844.94617
CLARK 867.94617
MILLER 835.37474
Copyright © 2004, Oracle. All rights reserved.
- 85. Explicit Data Type Conversion
TO_NUMBER TO_DATE
NUMBER CHARACTER DATE
TO_CHAR TO_CHAR
Copyright © 2004, Oracle. All rights reserved.
- 86. Modifying the Display Format of
Dates
Tuesday the 27th of January, 1998
27-JAN-98 January 27, 1998
01/27/98
Copyright © 2004, Oracle. All rights reserved.
- 87. TO_CHAR Function with Dates
TO_CHAR(date, 'fmfmt')
The format model:
The format model:
–
– Is case sensitive and must be enclosed in single
Is case sensitive and must be enclosed in single
quotation marks
quotation marks
–
– Can include any valid date format element
Can include any valid date format element
–
– Has an fm element to remove padded blanks or
Has an fm element to remove padded blanks or
suppress leading zeros
suppress leading zeros
–
– Is separated from the date value by a comma
Is separated from the date value by a comma
Copyright © 2004, Oracle. All rights reserved.
- 88. Date Format Model Elements
YYYY Full year in numbers
YEAR Year spelled out
MM 2-digit value for month
MONTH Full name of the month
3-letter abbreviation of the day
DY
of the week
DAY Full name of the day
Copyright © 2004, Oracle. All rights reserved.
- 89. Using the TO_CHAR Function with
Dates
SQL> SELECT ename, TO_CHAR(hiredate, 'Month DDth, YYYY')
2 AS HIREDATE
3 FROM emp
4 WHERE job='MANAGER';
ENAME HIREDATE
---------- --------------------
BLAKE May 01st, 1981
CLARK June 09th, 1981
JONES April 02nd, 1981
Copyright © 2004, Oracle. All rights reserved.
- 90. Using the TO_CHAR Function with
Dates
SQL> SELECT empno, TO_CHAR(hiredate, 'MM/YY') AS MONTH
2 FROM emp
3 WHERE ename='BLAKE';
EMPNO MONTH
--------- -----
7698 05/81
Copyright © 2004, Oracle. All rights reserved.
- 91. Using the TO_CHAR Function with
Dates
SQL> SELECT ename,
2 TO_CHAR(hiredate, 'fmDD Month YYYY') AS HIREDATE
3 FROM emp;
ENAME HIREDATE
---------- -----------------
KING 17 November 1981
BLAKE 1 May 1981
CLARK 9 June 1981
JONES 2 April 1981
MARTIN 28 September 1981
ALLEN 20 February 1981
...
14 rows selected.
Copyright © 2004, Oracle. All rights reserved.
- 92. Using the TO_CHAR Function with
Dates
SQL> SELECT ename, mgr, sal,TO_CHAR(hiredate,'YYYY-MON-DD')
2 AS HIREDATE
3 FROM emp
4 WHERE sal<1000
5 AND hiredate like '%80';
ENAME MGR SAL HIREDATE
---------- --------- --------- -----------
SMITH 7902 800 1980-DEC-17
Copyright © 2004, Oracle. All rights reserved.
- 93. Using the TO_CHAR Function with
Dates
SQL> SELECT empno,ename,deptno,TO_CHAR(hiredate,'MM-DD-YYYY')
2 AS HIREDATE
3 FROM emp
4 WHERE hiredate NOT LIKE '%81';
EMPNO ENAME DEPTNO HIREDATE
-------- ---------- --------- -----------
7369 SMITH 20 12-17-1980
7788 SCOTT 20 12-09-1982
7876 ADAMS 20 01-12-1983
7934 MILLER 10 01-23-1982
Copyright © 2004, Oracle. All rights reserved.
- 94. Using the TO_CHAR Function with
Dates
SQL> SELECT ename, job, deptno,
2 TO_CHAR(hiredate,'DD-MON-YYYY') AS HIRE_DATE
3 FROM emp
4 ORDER BY hiredate DESC;
ENAME JOB DEPTNO HIRE_DATE
---------- --------- --------- -----------
ADAMS CLERK 20 12-JAN-1983
SCOTT ANALYST 20 09-DEC-1982
MILLER CLERK 10 23-JAN-1982
JAMES CLERK 30 03-DEC-1981
FORD ANALYST 20 03-DEC-1981
KING PRESIDENT 10 17-NOV-1981
MARTIN SALESMAN 30 28-SEP-1981
...
14 rows selected.
Copyright © 2004, Oracle. All rights reserved.
- 95. Date Format Model Elements
• Time elements format the time portion of the date.
Time elements format the time portion of the date.
HH24:MI:SS AM 15:45:32 PM
DD "of" MONTH 12 of OCTOBER
ddspth fourteenth
Copyright © 2004, Oracle. All rights reserved.
- 96. Using Format Models to Display Time
SQL> SELECT TO_CHAR(SYSDATE,'HH24:MI:SS') TIME
2 FROM DUAL;
TIME
--------
13:55:46
Copyright © 2004, Oracle. All rights reserved.
- 97. TO_CHAR Function with Numbers
TO_CHAR(n,'fmt')
Use these formats with the TO_CHAR function to
Use these formats with the TO_CHAR function to
display a number value as a character:
display a number value as a character:
9 Represents a number
0 Forces a zero to be displayed
$ Places a floating dollar sign
L Uses the floating local currency symbol
. Prints a decimal point
, Places a thousand indicator
Copyright © 2004, Oracle. All rights reserved.
- 98. Using the TO_CHAR Function with
Numbers
SQL> SELECT TO_CHAR(sal,'$99,999') SALARY
2 FROM emp
3 WHERE ename = 'SCOTT';
SALARY
--------
$3,000
Thousand indicator
Dollar sign
Copyright © 2004, Oracle. All rights reserved.
- 99. Using the TO_NUMBER and
TO_DATE Functions
–
– Convert a character string to a number data type using the
Convert a character string to a number data type using the
TO_NUMBER function
TO_NUMBER function
TO_NUMBER(char)
• Convert a character string to a date data
• Convert a character string to a date data
type using the TO_DATE function
type using the TO_DATE function
TO_DATE(char[, 'fmt'])
Copyright © 2004, Oracle. All rights reserved.
- 100. Using the TO_NUMBER Function
SQL> SELECT TO_NUMBER('1000')+sal AS NEW_SALARY
2 FROM emp
3 WHERE ename = 'SCOTT';
NEW_SALARY
----------
4000
Copyright © 2004, Oracle. All rights reserved.
- 101. Date Functions
FUNCTION DESCRIPTION
MONTHS_BETWEEN Number of months
between two dates
ADD_MONTHS Adds calendar months to
date
NEXT_DAY Next day following the date
specified
LAST_DAY Last day of the month
ROUND Round off date
TRUNC Truncate date
Copyright © 2004, Oracle. All rights reserved.
- 102. Using Date Functions
Use the ADD_MONTHS function to add months to
Use the ADD_MONTHS function to add months to
a date.
a date.
SQL> SELECT ename, hiredate, ADD_MONTHS(hiredate, 6)
2 AS "+6 MONTHS"
3 FROM emp
4 WHERE ename='BLAKE';
ENAME HIREDATE +6 MONTHS
---------- --------- ---------
BLAKE 01-MAY-81 01-NOV-81
Copyright © 2004, Oracle. All rights reserved.
- 103. Nesting Functions
–
– Single-row functions can be nested to any level.
Single-row functions can be nested to any level.
–
– Nested functions are evaluated from the innermost level to
Nested functions are evaluated from the innermost level to
the outermost level.
the outermost level.
F3(F2(F1(col,arg1),arg2),arg3)
Step 1 = Result 1
Step 2 = Result 2
Step 3 = Result 3
Copyright © 2004, Oracle. All rights reserved.
- 104. Nesting Functions
Result 2
Result 1
SQL> SELECT ename,
2 NVL(TO_CHAR(mgr),'No Manager')
3 FROM emp
4 WHERE mgr IS NULL;
ENAME NVL(TO_CHAR(MGR),'NOMANAGER')
---------- -----------------------------
KING No Manager
Copyright © 2004, Oracle. All rights reserved.
- 105. Nesting Functions
SQL> SELECT MONTHS_BETWEEN
2 (TO_DATE('02-02-1995','MM-DD-YYYY'),
3 TO_DATE('01-01-1995','MM-DD-YYYY'))
4 "Months"
5 FROM DUAL;
Months
----------
1.03225806
Copyright © 2004, Oracle. All rights reserved.
- 106. Displaying Data
from Multiple Tables
Copyright © 2004, Oracle. All rights reserved.
- 107. Obtaining Data from Multiple Tables
Obtaining Data from Multiple Tables
EMP DEPT
EMPNO ENAME ... DEPTNO DEPTNO DNAME LOC
------ ----- ... ------ ------ ---------- --------
7839 KING ... 10 10 ACCOUNTING NEW YORK
7698 BLAKE ... 30 20 RESEARCH DALLAS
... 30 SALES CHICAGO
7934 MILLER ... 10 40 OPERATIONS BOSTON
EMPNO DEPTNO LOC
----- ------- --------
7839 10 NEW YORK
7698 30 CHICAGO
7782 10 NEW YORK
7566 20 DALLAS
7654 30 CHICAGO
7499 30 CHICAGO
Copyright © 2004, Oracle. All rights reserved.
- 108. Joining Tables
Use a join to query data from more than one table:
Use a join to query data from more than one table:
SELECT table1.column1, table2.column2
FROM table1, table2
WHERE Write the join condition in the WHERE clause.
table1.column1 = table2.column2;
– Write the join condition in the WHERE clause.
–
–
– Prefix the column name with the table name when the
Prefix the column name with the table name when the
same column name appears in more than one table.
same column name appears in more than one table.
Copyright © 2004, Oracle. All rights reserved.
- 109. Types of Joins
Equijoin Nonequijoin Self join
Equijoin Nonequijoin Self join
Copyright © 2004, Oracle. All rights reserved.
- 110. What Is an Equijoin?
EMP
EMPNO ENAME DEPTNO
------ ------- -------
... DEPT
7782 CLARK 10
DEPTNO DNAME LOC
------- ---------- --------
...
10 ACCOUNTING NEW YORK
...
Links rows that satisfy a specified condition
WHERE emp.deptno=dept.deptno
Copyright © 2004, Oracle. All rights reserved.
- 111. Equijoin
EMP DEPT
EMPNO ENAME DEPTNO DEPTNO DNAME LOC
------ ------- ------- ------- ---------- --------
7839 KING 10 10 ACCOUNTING NEW YORK
7698 BLAKE 30 30 SALES CHICAGO
7782 CLARK 10 10 ACCOUNTING NEW YORK
7566 JONES 20 20 RESEARCH DALLAS
7654 MARTIN 30 30 SALES CHICAGO
7499 ALLEN 30 30 SALES CHICAGO
7844 TURNER 30 30 SALES CHICAGO
7900 JAMES 30 30 SALES CHICAGO
7521 WARD 30 30 SALES CHICAGO
7902 FORD 20 20 RESEARCH DALLAS
7369 SMITH 20 20 RESEARCH DALLAS
... ...
14 rows selected. 14 rows selected.
Foreign key Primary key
Copyright © 2004, Oracle. All rights reserved.
- 112. Retrieving Records
with an Equijoin
SQL> SELECT emp.empno, emp.ename, emp.deptno,
2 dept.deptno, dept.loc
3 FROM emp, dept
4 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.
Copyright © 2004, Oracle. All rights reserved.
- 113. Qualifying Ambiguous
Column Names
–
– Use table prefixes to qualify column names that are in
Use table prefixes to qualify column names that are in
multiple tables.
multiple tables.
–
– Use table prefixes to improve performance.
Use table prefixes to improve performance.
Copyright © 2004, Oracle. All rights reserved.
- 114. Additional Search Conditions
Using the AND Operator
EMP DEPT
EMPNO ENAME DEPTNO DEPTNO DNAME LOC
------ ------- ------- ------ --------- --------
7839 KING 10 10 ACCOUNTING NEW YORK
7698 BLAKE 30 30 SALES CHICAGO
7782 CLARK 10 10 ACCOUNTING NEW YORK
7566 JONES 20 20 RESEARCH DALLAS
7654 MARTIN 30 30 SALES CHICAGO
7499 ALLEN 30 30 SALES CHICAGO
7844 TURNER 30 30 SALES CHICAGO
7900 JAMES 30 30 SALES CHICAGO
... ...
14 rows selected. 14 rows selected.
WHERE emp.deptno=dept.deptno AND ename='KING'
Copyright © 2004, Oracle. All rights reserved.
- 115. Using Additional Search Conditions
with a Join
SQL> SELECT emp.empno, emp.ename, emp.deptno, dept.loc
2 FROM emp, dept;
3 WHERE emp.deptno = dept.deptno
4 AND emp.ename = 'KING';
EMPNO ENAME DEPTNO LOC
--------- ---------- --------- -------------
7839 KING 10 NEW YORK
Copyright © 2004, Oracle. All rights reserved.
- 116. Using Additional Search Conditions
with a Join
SQL> SELECT emp.ename, emp.job, dept.deptno, dept.dname
2 FROM emp, dept
3 WHERE emp.deptno=dept.deptno
4 AND emp.job IN ('MANAGER','PRESIDENT');
ENAME JOB DEPTNO DNAME
---------- --------- --------- --------------
KING PRESIDENT 10 ACCOUNTING
BLAKE MANAGER 30 SALES
CLARK MANAGER 10 ACCOUNTING
JONES MANAGER 20 RESEARCH
Copyright © 2004, Oracle. All rights reserved.
- 117. Table Aliases
Simplify queries by using table aliases.
Simplify queries by using table aliases.
SQL> SELECT emp.empno, emp.ename, emp.deptno,
2 dept.deptno, dept.loc
3 FROM emp, dept
4 WHERE emp.deptno=dept.deptno;
… can be written as ...
… can be written as ...
SQL> SELECT e.empno, e.ename, e.deptno,
2 d.deptno, d.loc
3 FROM emp e, dept d
4 WHERE e.deptno=d.deptno;
Copyright © 2004, Oracle. All rights reserved.
- 118. Using Table Aliases
SQL> SELECT e.empno, e.ename, e.deptno,
2 d.deptno, d.loc
3 FROM emp e, dept d
4 WHERE e.deptno=d.deptno;
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
7654 MARTIN 30 30 CHICAGO
7499 ALLEN 30 30 CHICAGO
...
14 rows selected.
Copyright © 2004, Oracle. All rights reserved.
- 119. Nonequijoins
EMP SALGRADE
EMPNO ENAME SAL GRADE LOSAL HISAL
------ ------- ------ ----- ----- ------
7839 KING 5000 1 700 1200
7698 BLAKE 2850 2 1201 1400
7782 CLARK 2450 3 1401 2000
7566 JONES 2975 4 2001 3000
7654 MARTIN 1250 5 3001 9999
7499 ALLEN 1600
7844 TURNER 1500
7900 JAMES 950
... Salary in the EMP
14 rows selected. table is between
low salary and high
salary in the SALGRADE
table.
Copyright © 2004, Oracle. All rights reserved.
- 120. Retrieving Records
with Nonequijoins
SQL> SELECT e.ename, e.sal, s.grade
2 FROM emp e, salgrade s
3 WHERE e.sal
4 BETWEEN s.losal AND s.hisal;
ENAME SAL GRADE
---------- --------- ---------
JAMES 950 1
SMITH 800 1
ADAMS 1100 1
...
14 rows selected.
Copyright © 2004, Oracle. All rights reserved.
- 121. Joining More Than Two Tables
EMP DEPT
ENAME SAL DEPTNO DEPTNO DNAME
---------- --------- --------- --------- ----------
JAMES 950 30 10 ACCOUNTING
SMITH 800 20 20 RESEARCH
ADAMS 1100 20 30 SALES
MARTIN 1250 30 40 OPERATIONS
WARD 1250 30
MILLER 1300 10
… SALGRADE
14 rows selected. LOSAL HISAL GRADE
--------- --------- ---------
700 1200 1
WHERE emp.sal BETWEEN 1201 1400 2
salgrade.losal AND 1401 2000 3
salgrade.hisal 2001 3000 4
AND emp.deptno = dept.deptno 3001 9999 5
Copyright © 2004, Oracle. All rights reserved.
- 122. Using Multiple Joins
SQL> SELECT e.ename, e.deptno, d.dname, e.sal, s.grade
2 FROM emp e, dept d, salgrade s
3 WHERE e.deptno=d.deptno
4 AND e.sal BETWEEN s.losal and s.hisal;
ENAME DEPTNO DNAME SAL GRADE
---------- --------- -------------- --------- ---------
JAMES 30 SALES 950 1
SMITH 20 RESEARCH 800 1
ADAMS 20 RESEARCH 1100 1
MARTIN 30 SALES 1250 2
WARD 30 SALES 1250 2
MILLER 10 ACCOUNTING 1300 2
ALLEN 30 SALES 1600 3
...
14 rows selected.
Copyright © 2004, Oracle. All rights reserved.
- 123. Selfjoins
EMP (WORKER) EMP (MANAGER)
EMPNO ENAME MGR EMPNO ENAME
----- ------ ---- ----- --------
7839 KING
7698 BLAKE 7839 7839 KING
7782 CLARK 7839 7839 KING
7566 JONES 7839 7839 KING
7654 MARTIN 7698 7698 BLAKE
7499 ALLEN 7698 7698 BLAKE
MGR in the WORKER table is equal to EMPNO in the
MANAGER table.
Copyright © 2004, Oracle. All rights reserved.
- 124. Joining a Table to Itself
SQL> SELECT worker.ename||' works for '||manager.ename
2 AS WHO_WORKS_FOR_WHOM
3 FROM emp worker, emp manager
4 WHERE worker.mgr = manager.empno;
WHO_WORKS_FOR_WHOM
-------------------------------
BLAKE works for KING
CLARK works for KING
JONES works for KING
MARTIN works for BLAKE
...
13 rows selected.
Copyright © 2004, Oracle. All rights reserved.
- 125. Aggregating Data
by Using Group Functions
Copyright © 2004, Oracle. All rights reserved.
- 126. What Are Group Functions?
Group functions operate on sets of rows to give one result
Group functions operate on sets of rows to give one result
per group.
per group.
EMP
DEPTNO SAL
--------- ---------
10 2450
10 5000
10 1300
20 800
20 1100
20 3000 maximum MAX(SAL)
20 3000 salary in ---------
20 2975 the EMP table 5000
30 1600
30 2850
30 1250
30 950
30 1500
30 1250
Copyright © 2004, Oracle. All rights reserved.
- 127. Types of Group Functions
–
– AVG
AVG
–
– COUNT
COUNT
–
– MAX
MAX
–
– MIN
MIN
–
– SUM
SUM
Copyright © 2004, Oracle. All rights reserved.
- 128. Guidelines for Using Group
Functions
Many aggregate functions accept these
Many aggregate functions accept these
options:
options:
– DISTINCT
– DISTINCT
– ALL
– ALL
– NVL
– NVL
Copyright © 2004, Oracle. All rights reserved.
- 129. Using the AVG and SUM Functions
You can use AVG and SUM for numeric data.
You can use AVG and SUM for numeric data.
SQL> SELECT AVG(sal), SUM(sal)
2 FROM emp
3 WHERE job LIKE 'SALES%';
AVG(SAL) SUM(SAL)
-------- ---------
1400 5600
Copyright © 2004, Oracle. All rights reserved.
- 130. Using the MIN and MAX Functions
You can use MIN and MAX for any data type.
You can use MIN and MAX for any data type.
SQL> SELECT TO_CHAR(MIN(hiredate),'DD-MON-YYYY'),
2 TO_CHAR(MAX(hiredate),'DD-MON-YYYY')
3 FROM emp;
T0_CHAR(MIN TO_CHAR(MAX
--------- ---------
17-DEC-1980 12-JAN-1983
Copyright © 2004, Oracle. All rights reserved.
- 131. Using the MIN and MAX Functions
You can use MIN and MAX for any data type.
You can use MIN and MAX for any data type.
SQL> SELECT MIN(sal) AS "Lowest Salary",
2 MAX(sal) AS "Highest Salary"
3 FROM emp;
Lowest Salary Highest Salary
------------- --------------
800 5000
Copyright © 2004, Oracle. All rights reserved.
- 132. Using the COUNT Function
COUNT(*) returns the number of rows in a query.
COUNT(*) returns the number of rows in a query.
SQL> SELECT COUNT(*)
2 FROM emp
3 WHERE deptno = 30;
COUNT(*)
---------
6
Copyright © 2004, Oracle. All rights reserved.
- 133. Using the COUNT Function
COUNT(expr) returns the number of nonnull rows.
COUNT(expr) returns the number of nonnull rows.
SQL> SELECT COUNT(comm)
2 FROM emp
3 WHERE deptno = 30;
COUNT(COMM)
-----------
4
Copyright © 2004, Oracle. All rights reserved.
- 134. Group Functions and Null Values
Group functions ignore null values in the column.
Group functions ignore null values in the column.
SQL> SELECT AVG(comm)
2 FROM emp;
AVG(COMM)
---------
550
Copyright © 2004, Oracle. All rights reserved.
- 135. Using the NVL Function
with Group Functions
The NVL function forces group functions to include
The NVL function forces group functions to include
null values.
null values.
SQL> SELECT AVG(NVL(comm,0))
2 FROM emp;
AVG(NVL(COMM,0))
----------------
157.14286
Copyright © 2004, Oracle. All rights reserved.
- 136. Using the NVL Function
with Group Functions
Average commission for all people hired in 1981
Average commission for all people hired in 1981
SQL> SELECT AVG(NVL(comm,0))
2 FROM emp
3 WHERE hiredate
4 BETWEEN TO_DATE('01-JAN-1981','DD-MON-YYYY')
5 AND TO_DATE('31-DEC-1981','DD-MON-YYYY');
AVG(NVL(COMM,0))
----------------
220
Copyright © 2004, Oracle. All rights reserved.
- 137. Creating Groups of Data
EMP
DEPTNO SAL
--------- ---------
10 2450
10 5000 2916.6667
10 1300
20 800 average DEPTNO AVG(SAL)
20 1100 salary ------- ---------
20 3000 2175 in EMP
10 2916.6667
20 3000 table
20 2975 for each 20 2175
30 1600 department 30 1566.6667
30 2850
30 1250 1566.6667
30 950
30 1500
30 1250
Copyright © 2004, Oracle. All rights reserved.
- 138. Creating Groups of Data:
GROUP BY Clause
Use the GROUP BY clause to divide rows in a table
Use the GROUP BY clause to divide rows in a table
into smaller groups.
into smaller groups.
SELECT column, group_function
FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[ORDER BY column];
Copyright © 2004, Oracle. All rights reserved.
- 139. Using the GROUP BY Clause
All columns in the SELECT list that are not in group
All columns in the SELECT list that are not in group
functions must be in the GROUP BY clause.
functions must be in the GROUP BY clause.
SQL> SELECT deptno, AVG(sal)
2 FROM emp
3 GROUP BY deptno;
DEPTNO AVG(SAL)
--------- ---------
10 2916.6667
20 2175
30 1566.6667
Copyright © 2004, Oracle. All rights reserved.
- 140. Using the GROUP BY Clause
The GROUP BY column does not have to be in the
The GROUP BY column does not have to be in the
SELECT list.
SELECT list.
SQL> SELECT AVG(sal)
2 FROM emp
3 GROUP BY deptno;
AVG(SAL)
---------
2916.6667
2175
1566.6667
Copyright © 2004, Oracle. All rights reserved.
- 141. Using the GROUP BY Clause
Display the number of people in each department.
Display the number of people in each department.
SQL> SELECT deptno, COUNT(*) AS "Dept Employees"
2 FROM emp
3 GROUP BY deptno;
DEPTNO Dept Employees
--------- --------------
10 3
20 5
30 6
Copyright © 2004, Oracle. All rights reserved.
- 142. Using a Group Function in the
ORDER BY Clause
SQL> SELECT deptno, AVG(sal)
2 FROM emp
3 GROUP BY deptno
4 ORDER BY AVG(sal);
DEPTNO AVG(SAL)
---------- ------------
30 1566.6667
20 2175
10 2916.6667
Copyright © 2004, Oracle. All rights reserved.
- 143. Illegal Queries
Using Group Functions
Any column or expression in the SELECT list that is
Any column or expression in the SELECT list that is
not an aggregate function must be in the GROUP BY
not an aggregate function must be in the GROUP BY
clause.
clause. usse
e
lla u
ca
Yc
BY
PB
UP
SQL> SELECT deptno, COUNT(ename)
SQL> SELECT deptno, COUNT(ename) OU
RO
2 FROM
2 FROM emp;
emp;
eG GR
tth e
h
n
in
SELECT deptno, COUNT(ename) g i
SELECT deptno, COUNT(ename) g
*
* iis
s siin
sn
ERROR at line 1: m
ERROR at line 1:
nm
n
ORA-00937: not a single-group group function
um
llu m
ORA-00937: not a single-group group function
Co
Co
Copyright © 2004, Oracle. All rights reserved.
- 145. The Set Operators
A B
Intersect
A B A B
Union / Union All
A B
Minus
Copyright © 2004, Oracle. All rights reserved.
- 146. Tables Used in This Lesson
EMP
EMPNO ENAME
EMPNO ENAME JOB
JOB MGR HIREDATE
MGR HIREDATE SAL
SAL COMM
COMM
DEPTNO
DEPTNO
--------- ---------- --------- --------- --------- ---------
--------- ---------- --------- --------- --------- --------- --------- --------
--------- --------
-
-
7839 KING
7839 KING PRESIDENT
PRESIDENT 17-NOV-81
17-NOV-81 5000
5000
10
10
7698 BLAKE
7698 BLAKE MANAGER
MANAGER 7839 01-MAY-81
7839 01-MAY-81 2850
2850
30
30
7782 CLARK
7782 CLARK MANAGER
MANAGER 7839 09-JUN-81
7839 09-JUN-81 1500
1500
10
10
7566 JONES
7566 JONES MANAGER
MANAGER 7839 02-APR-81
7839 02-APR-81 2975
2975
20
20 EMPID NAME
EMPID NAME TITLE
TITLE DATE_OUT
DATE_OUT
7654 MARTIN
7654 MARTIN SALESMAN DEPTID 7698 28-SEP-81
SALESMAN DEPTID 7698 28-SEP-81 1250
1250 1400
1400
30
30 --------- --------------------
--------- -------------------- ---------
--------- --------- --------
--------- --------
7499 ALLEN
7499 ALLEN SALESMAN -
SALESMAN - 7698 20-FEB-81
7698 20-FEB-81 1600
1600 300
300
30
30 6087 SPENCER
6087 SPENCER OPERATOR
OPERATOR 27-NOV-81
27-NOV-81
7844 TURNER
7844 TURNER SALESMAN 20
SALESMAN 20 7698 08-SEP-81
7698 08-SEP-81 1500
1500 0
0
30
30 6185 VANDYKE
6185 VANDYKE MANAGER
MANAGER 17-JAN-81
17-JAN-81
7900 JAMESEMP_HISTORY 10
7900 JAMES CLERK
CLERK 10 7698 03-DEC-81
7698 03-DEC-81 950
950
30
30 6235 BALFORD
6235 BALFORD CLERK
CLERK 22-FEB-80
22-FEB-80
7521 WARD
7521 WARD SALESMAN 20
SALESMAN 20 7698 22-FEB-81
7698 22-FEB-81 1250
1250 500
500
30
30 7788 SCOTT
7788 SCOTT ANALYST
ANALYST 05-MAY-81
05-MAY-81
7902 FORD
7902 FORD ANALYST 20
ANALYST 20 7566 03-DEC-81
7566 03-DEC-81 3000
3000
20
20 7001 JEWELL
7001 JEWELL ANALYST
ANALYST 10-JUN-81
10-JUN-81
7369 SMITH All rights reserved.
Copyright © 2004, SMITH
7369 Oracle. CLERK
CLERK 30
30 7902 17-DEC-80
7902 17-DEC-80 800
800
20
20 7499 ALLEN
7499 ALLEN SALESMAN 01-AUG-80
SALESMAN 01-AUG-80
- 147. UNION
A B
Copyright © 2004, Oracle. All rights reserved.