Download as pdf or txt
Download as pdf or txt
You are on page 1of 87

Chapter No 5

SQL Functions
Objectives

• After completing this lesson, you


should be able to do the following:
– Describe various types of functions
available in SQL
– Use character, number, and date
functions in SELECT statements
– Describe the use of conversion functions
5.2 What is a Function

Input Output
Function

arg 1 Function
performs action
arg 2
Result
value

arg n
Two Types of SQL Functions

Functions

Single-row Multiple-row
functions functions
Single-Row Functions
• Manipulate data items
• Accept arguments and return one value
• Act on each row returned
• Return one result per row
• May modify the datatype
• Can be nested

function_name (column|expression, [arg1, arg2,...])


Single-Row Functions

Character

General Number
Single-row
functions

Conversion Date
5.4.1 Character Functions
Character
functions

Case conversion Character manipulation


functions functions
LOWER CHR LTRIM
UPPER CONCAT RTRIM
INITCAP SUBSTR REPLACE
LENGTH USER
INSTR
LPAD
RPAD
TRIM
5.4.1.1 CHR Function
Syntax: CHR (n) Purpose: Returns the character with the
binary equivalent to n in the database character set.

SELECT CHR(83)||CHR(81)||CHR(76)
FROM dual

CHR
---
SQL
5.4.1.2 CONCAT Function
Syntax : CONCAT(char1, char2) Purpose: Returns char1
concatenated with char2, where char1 and char2 are
string arguments. This function is equivalent to the
concatenation operator (||)studied in chapter 2.
SELECT CONCAT(ename ,deptno)
FROM emp

CONCAT(ENAME,DEPTNO)
--------------------
SMITH20
ALLEN30
WARD30
JONES20
MARTIN30
5.4.1.3 INITCAP Function
INITCAP(char) Purpose: Returns char, with the first
letter of each word in uppercase and all other letters in
lowercase. Words are delimited by white space or
characters that are not alphanumeric.
SELECT INITCAP(ename) ename, INITCAP(job) job
FROM emp

ENAME JOB
---------- ---------
SMITH CLERK
ALLEN SALESMAN
WARD SALESMAN
JONES MANAGER
5.4.1.4 LOWER Function
LOWER(char) Purpose: Returns a string argument
char, with all its letters in lowercase. The return
value has the same datatype as char, either CHAR
or VARCHAR2.

SELECT LOWER(ename) ename, LOWER(job) job


FROM emp

ENAME JOB
---------- ---------
smith clerk
allen salesman
ward salesman
jones manager
martin salesman
blake manager
5.4.1.5 UPPER Function
UPPER(char) Purpose: Returns the string argument
char with all its letters converted to uppercase. The
return value has the same datatype as char.

SELECT UPPER(ename) ename, UPPER(job) job


FROM emp

ENAME JOB
---------- ---------
SMITH CLERK
ALLEN SALESMAN
WARD SALESMAN
JONES MANAGER
MARTIN SALESMAN
BLAKE MANAGER
5.4.1.6 LPAD Function
LPAD(char1,n [,char2]) Purpose: Pads the character
value as right-justified. Returns char1, left-padded to
length n with the sequence of characters in char2; char2
defaults to a single blank. If char1 is longer than n, this
function returns the portion of char1 that fits in n.
SELECT LPAD(ename,20 ,'*') ename , LPAD(sal,15,'$') sal ,
LPAD(hiredate,15,'*') hiredate
FROM emp
ENAME SAL HIREDATE
-------------------- --------------- ---------------
***************SMITH $$$$$$$$$$$$800 ******17-DEC-80
***************ALLEN $$$$$$$$$$$1600 ******20-FEB-81
****************WARD $$$$$$$$$$$1250 ******22-FEB-81
***************JONES $$$$$$$$$$$2975 ******02-APR-81
5.4.1.7 RPAD Function
RPAD(char1,n [,char2]) This works the same as the
previous function; the only difference is that LPAD puts
the padding on the left side and RPAD puts the padding
on the right side.
SELECT RPAD(ename,20 ,'*') ename , RPAD(sal,15,'$') sal ,
RPAD(hiredate,15,'*') hiredate
FROM emp

ENAME SAL HIREDATE


-------------------- --------------- ---------------
SMITH*************** 800$$$$$$$$$$$$ 17-DEC-80******
ALLEN*************** 1600$$$$$$$$$$$ 20-FEB-81******
WARD**************** 1250$$$$$$$$$$$ 22-FEB-81******
JONES*************** 2975$$$$$$$$$$$ 02-APR-81******
5.4.1.8 LTRIM Function
LTRIM(char [, set])Purpose: Returns the string
argument char, with its left-most characters removed up
to the first character not in the string argument set,
which defaults to a single space

SELECT ename , LTRIM(ename , 'LA’)


FROM emp

ENAME LTRIM(ENAM
---------- ----------
SMITH SMITH
ALLEN EN
WARD WARD
JONES JONES
MARTIN MARTIN
5.4.1.9 RTRIM Function
RTRIM(char [, set]) Purpose: This functions in the same
way as the previous function. LTRIM removes a character
from the left side while RTRIM removes it from the right side.
In other words, no character can end with the letter
mentioned in the set.
SELECT ename , RTRIM(ename , 'TH')
FROM emp

ENAME RTRIM(ENAM
---------- ----------
SMITH SMI
ALLEN ALLEN
WARD WARD
JONES JONES
MARTIN MARTIN
5.4.1.10 TRIM Function
TRIM( [[<trim_spec >] char ] FROM ] string This
function works for both LTRIM and RTRIM. Trim
removes the character mentioned from both leading and
ending sides

SELECT ename , TRIM('T' from ename )


FROM emp

ENAME TRIM('T'FR
---------- ----------
SMITH SMITH
ALLEN ALLEN
WARD WARD
JONES JONES
MARTIN MARTIN
5.4.1.11 REPLACE Function
REPLACE(char, search_string [ , replacement_String])
Returns char with every occurrence of search_string replaced
with replacement_string, where char, search_string, and
replacement_string are string arguments.

SELECT ename , REPLACE(ename ,'T','WA') NEW_NAME


FROM emp

ENAME NEW_NAME
---------- ---------------
SMITH SMIWAH
ALLEN ALLEN
WARD WARD
JONES JONES
MARTIN MARWAIN
5.4.1.12 SUBSTR Function
SUBSTR(char, m [, n ])Purpose: Sub means part, so this
function refers to part of the string. It returns a portion of
the string argument char, beginning with the character at
position m and n characters long.

SELECT ename , SUBSTR(ename ,3,2)


FROM emp

ENAME SU
---------- --
SMITH IT
ALLEN LE
WARD RD
JONES NE
MARTIN RT
5.4.1.13 USER Function
USER Purpose: This function returns the current schema
name as a character string.

SELECT USER
FROM DUAL;

USER
--------------
SCOTT
5.4.1.14 INSTR Function
INSTR(char1, char2, [, n [, m ]]) Searches the string
argument char1, beginning with its nth character, for the
mth occurrence of string argument char2, where m and n
are numeric arguments. Returns the position in char1 of
the first character of this occurrence

SELECT ename , INSTR(ename,'L',1,2) Altering


FROM emp

ENAME ALTERING
---------- ----------
SMITH 0
ALLEN 3
WARD 0
JONES 0
MARTIN 0
5.4.1.15 LENGTH Function
LENGTH (char) Purpose: Returns the length in
characters of the string argument char. If char has the
data type CHAR, the length includes all trailing
blanks. If char is null, it returns null.

SELECTename , LENGTH(ename)
FROM emp

ENAME LENGTH(ENAME)
---------- ---------------------
SMITH 5
ALLEN 5
WARD 4
JONES 5
MARTIN 6
5.4.2.1 CEIL Function
CEIL (n) Purpose: Returns the smallest integer
greater than or equal to n. Ceil means roof, so it
always selects the highest value.

SELECT ename ,sal/3.33 , CEIL(sal/3.33 )


FROM emp

ENAME SAL/3.33 CEIL(SAL/3.33)


---------- ---------- --------------
SMITH 240.24024 241
ALLEN 480.48048 481
WARD 375.375375 376
JONES 893.393393 894
MARTIN 375.375375 376
5.4.2.2 FLOOR Function
FLOOR (n) Returns the largest integer equal to or less
than n. Floor is the opposite of ceil; thus, it always selects
the lowest figure. In other words, it removes the fraction
part and shows the lowest value.

•SELECT ename ,sal/3.33 , FLOOR(sal/3.33 )


•FROM emp

ENAME SAL/3.33 FLOOR(SAL/3.33)


---------- ---------- ---------------
SMITH 240.24024 240
ALLEN 480.48048 480
WARD 375.375375 375
JONES 893.393393 893
MARTIN 375.375375 375
5.4.2.3 TRUNC Function
TRUNC(n [, m]) Purpose: Returns n truncated to m decimal
places, where m and n are numeric arguments. If m is omitted,
the function truncates it to 0 places. If m is negative, it truncates
(makes zero) m digits to the left of the decimal point. TRUNC
also works like floor. However, in TRUNC you can specify the
number of decimal places, unlike in FLOOR.
SELECT ename ,sal/3.33 , TRUNC(sal/3.33 , 2)
FROM emp

ENAME SAL/3.33 TRUNC(SAL/3.33,2)


---------- ---------- -----------------
SMITH 240.24024 240.24
ALLEN 480.48048 480.48
WARD 375.375375 375.37
JONES 893.393393 893.39
MARTIN 375.375375 375.37
Using the TRUNC Function

SQL> SELECT TRUNC(45.923,2), TRUNC(45.923),


2 TRUNC(45.923,-1)
3 FROM DUAL;

TRUNC(45.923,2) TRUNC(45.923) TRUNC(45.923,-1)


--------------- ------------- ---------------
45.92 45 40
5.4.2.4 ROUND Function
ROUND(n [,m ])Purpose: Round is a mathematical function
that works exactly as the round function in mathematics. If a
decimal is more than half, it will take the next highest figure;
if the value is less than half, it will take the next lowest figure.

SELECT ename ,sal/3.3 , TRUNC(sal/3.3 , 2) , ROUND(sal/3.3,2)


FROM emp

ENAME SAL/3.33 TRUNC(SAL/3.33,2) ROUND(SAL/3.33,2)


---------- ---------- ----------------- -----------------
SMITH 240.24024 240.24 240.24
ALLEN 480.48048 480.48 480.48
WARD 375.375375 375.37 375.38
JONES 893.393393 893.39 893.39
MARTIN 375.375375 375.37 375.38
Using the ROUND Function

SQL> SELECT ROUND(45.923,2), ROUND(45.923,0),


2 ROUND(45.923,-1)
3 FROM DUAL;

ROUND(45.923,2) ROUND(45.923,0) ROUND(45.923,-1)


--------------- -------------- -----------------
45.92 46 50
5.4.2.5 MOD Function
MOD (m,n) Purpose: Returns the remainder of m divided
by n. Returns m if n is .

SELECT sal , MOD(sal,500)


FROM emp

SAL MOD(SAL,500)
--------- ------------
800 300
1600 100
1250 250
2975 475
1250 250
Using the MOD Function
• Calculate the remainder of the ratio of
salary to commission for all
employees whose job title is
salesman.
SQL> SELECT ename, sal, comm, MOD(sal, comm)
2 FROM emp
3 WHERE job = 'SALESMAN';

ENAME SAL COMM MOD(SAL,COMM)


---------- --------- --------- -------------
MARTIN 1250 1400 1250
ALLEN 1600 300 100
TURNER 1500 0 1500
WARD 1250 500 250
Working with Dates
• Oracle stores dates in an internal
numeric format: century, year, month,
day, hours, minutes, seconds.
• The default date format is DD-MON-
YY.
• SYSDATE is a function returning date
and time.
• DUAL is a dummy table used to view
SYSDATE.
Arithmetic with Dates

• Add or subtract a number to or from a


date for a resultant date value.
• Subtract two dates to find the number
of days between those dates.
• Add hours to a date by dividing the
number of hours by 24.
Using Arithmetic Operators
with Dates

SQL> SELECT ename, (SYSDATE-hiredate)/7 WEEKS


2 FROM emp
3 WHERE deptno = 10;

ENAME WEEKS
---------- ---------
KING 830.93709
CLARK 853.93709
MILLER 821.36566
5.4.3.1 ADD_MONTHS Function
ADD_MONTHS(d, n) d, a value of the Date datatype. n,
an integer that represents a number of months. Adds
a specified date d to a specified number of months n and
returns the resulting date.

SELECT ename ,hiredate , ADD_MONTHS(hiredate , 5)


FROM emp

ENAME HIREDATE ADD_MONTH


---------- --------- ---------
SMITH 17-Dec-80 17-May-81
ALLEN 20-Feb-81 20-Jul-81
WARD 22-Feb-81 22-Jul-81
JONES 2-Apr-81 2-Sep-81
MARTIN 28-Sep-81 28-Feb-82
5.4.3.2 CURRENT_DATE
Function
CURRENT_DATE Purpose: Returns the current date.

SELECT CURRENT_DATE
FROM DUAL

CURRENT_D
-------------------
30-Aug-08
5.4.3.3 SYSDATE Function
SYSDATE Purpose: Returns the current date and time.
Requires no arguments.

SELECT SYSDATE
FROM DUAL

SYSDATE
-------------------
30-Aug-08
5.4.3.4 LAST_DAY Function
LAST_DAY(d)Purpose: Returns a date that represents
the last day of the month in which date d occurs.

SELECT hiredate , LAST_DAY(hiredate)


FROM emp

HIREDATE LAST_DAY(
--------------- -----------------
17-Dec-80 31-Dec-80
20-Feb-81 28-Feb-81
22-Feb-81 28-Feb-81
2-Apr-81 30-Apr-81
28-Sep-81 30-Sep-81
5.4.3.5 NEXT_DAY Function
NEXT_DAY(d, char) Purpose: Returns the date of the first
weekday named by char that is later than the date d. The
argument char must be a day of the week in your session’s
date language. The return value has the same hours, minutes,
and seconds component as the argument d.
SELECT hiredate , NEXT_DAY(hiredate , 'SATURDAY')
FROM emp

HIREDATE NEXT_DAY(
--------------- -----------------
17-Dec-80 20-Dec-80
20-Feb-81 21-Feb-81
22-Feb-81 28-Feb-81
2-Apr-81 4-Apr-81
28-Sep-81 3-Oct-81
5.4.3.6 TRUNC Function
TRUNC(d [, fmt])Purpose: Returns the date d with its
time portion truncated to the time unit specified by the
format model fmt. If you omit fmt, then d is truncated

SELECT hiredate , TRUNC(hiredate ,'MONTH')BY_MONTH


,TRUNC(hiredate ,'YEAR') BY_YEAR
FROM emp

HIREDATE BY_MONTH BY_YEAR


--------- --------- ---------
17-Dec-80 1-Dec-80 1-Jan-80
20-Feb-81 1-Feb-81 1-Jan-81
22-Feb-81 1-Feb-81 1-Jan-81
2-Apr-81 1-Apr-81 1-Jan-81
28-Sep-81 1-Sep-81 1-Jan-81
5.4.3.7 ROUND Function
ROUND(d [,fmt]) Purpose: Returns d rounded to the unit
specified by the format model fmt. If you omit fmt, d is
rounded to the nearest day.

SELECT hiredate , ROUND(hiredate,'MONTH')BY_MONTH


,ROUND(hiredate ,'YEAR') BY_YEAR
FROM emp

HIREDATE BY_MONTH BY_YEAR


--------- --------- ---------
17-Dec-80 1-Jan-81 1-Jan-81
20-Feb-81 1-Mar-81 1-Jan-81
22-Feb-81 1-Mar-81 1-Jan-81
2-Apr-81 1-Apr-81 1-Jan-81
28-Sep-81 1-Oct-81 1-Jan-82
Using Date Functions

• ROUND('25-JUL-95','MONTH') 01-AUG-95

• ROUND('25-JUL-95','YEAR') 01-JAN-96

• TRUNC('25-JUL-95','MONTH') 01-JUL-95

• TRUNC('25-JUL-95','YEAR') 01-JAN-95
5.4.4 Conversion Functions

Datatype
conversion

Implicit datatype Explicit datatype


conversion conversion
Implicit Datatype Conversion

• For assignments, the Oracle Server


can automatically convert the
following:
From To
VARCHAR2 or CHAR NUMBER

VARCHAR2 or CHAR DATE

NUMBER VARCHAR2

DATE VARCHAR2
Implicit Datatype Conversion

• For expression evaluation, the Oracle


Server can automatically convert the
following:
From To
VARCHAR2 or CHAR NUMBER

VARCHAR2 or CHAR DATE


Explicit Datatype Conversion
TO_NUMBER TO_DATE

NUMBER CHARACTER DATE

TO_CHAR TO_CHAR
5.4.4.1 TO_CHAR Function

TO_CHAR(date, 'fmt')

• The format model:


• Must be enclosed in single quotation
marks and is case sensitive
• Can include any valid date format
element
• Has an fm element to remove padded
blanks or suppress leading zeros
• Is separated from the date value by a
comma
5.4.4.1 TO_CHAR Function
TO_CHAR(n [, fmt]) (Number Syntax) TO_CHAR(d [,
fmt]) (Date Syntax) Purpose: Converts a date or
number to a value of the VARCHAR2 data type using the
optional format fmt.
•SELECT TO_CHAR(SYSDATE,'DD,MONTH ,YEAR HH:MI:SS')
•FROM DUAL

TO_CHAR(SYSDATE,'DD,MONTH,YEARHH:MI:SS')
------------------------------------------
31,AUGUST ,TWO THOUSAND EIGHT 06:44:58
Elements of Date Format Model

YYYY Full year in numbers

YEAR Year spelled out

MM Two-digit value for month

MONTH Full name of the month


Three-letter abbreviation of the
DY
day of the week
DAY Full name of the day
Elements of Date Format
Model
• Time elements format the time portion
of the date.
HH24:MI:SS AM 15:45:32 PM

• Add character strings by enclosing


them in double quotation marks.
DD "of" MONTH 12 of OCTOBER
• Number suffixes spell out numbers.
ddspth fourteenth
5.4.4.1 TO_CHAR WITH
NUMBER Function

SELECT TO_CHAR(sal , '$9999999')


FROM emp

TO_CHAR(S
---------
$800
$1,600
$1,250
$2,975
$1,250
5.4.4.2 TO_DATE Function
TO_DATE(char [, fmt ])Purpose: Converts the character string
argument char to a value of the DATE datatype. The fmt
argument is a date format specifying the format of char. All
date and time formats used in the TO_CHAR function will be
used with TO_DATE as well.
SELECT ename , sal , job , hiredate
FROM emp
WHERE hiredate = TO_DATE('DECEMBER-03-1981','MONTH-DD-YYYY')

ENAME SALJOB HIREDATE


---------- ------------------- ---------
JAMES 950CLERK 3-Dec-81
FORD 3000ANALYST 3-Dec-81
5.4.4.3 TO_NUMBER Function
TO_NUMBER(char [, fmt ]) Purpose: Converts the string argument
char that contains a number in the format specified by the optional
format model fmt, to return a value of the NUMBER datatype. The
format model you choose will be based on the previously
demonstrated format elements.

SELECT TO_NUMBER('1234') + 66
FROM DUAL;

TO_NUMBER('1234')+66
--------------------
1300
5.4.5.1 DECODE Function

• Facilitates conditional inquiries by doing


the work of a CASE or IF-THEN-ELSE
statement
DECODE(col/expression, search1, result1
[, search2, result2,...,]
[, default])
Using the DECODE Function

SQL> SELECT job, sal,


2 DECODE(job, 'ANALYST', SAL*1.1,
3 'CLERK', SAL*1.15,
4 'MANAGER', SAL*1.20,
5 SAL)
6 REVISED_SALARY
7 FROM emp;

JOB SAL REVISED_SALARY


--------- --------- --------------
PRESIDENT 5000 5000
MANAGER 2850 3420
MANAGER 2450 2940
...
14 rows selected.
Using the DECODE Function
Display the applicable tax rate for each
employee in department 30.
SQL> SELECT ename, sal,
2 DECODE(TRUNC(sal/1000, 0),
3 0, 0.00,
4 1, 0.09,
5 2, 0.20,
6 3, 0.30,
7 4, 0.40,
8 5, 0.42,
9 6, 0.44,
10 0.45) TAX_RATE
11 FROM emp
12 WHERE deptno = 30;
5.4.5.2 NVL Function

• Converts null to an actual value


• Datatypes that can be used are date,
character, and number.
• Datatypes must match
• NVL(comm,0)
• NVL(hiredate,'01-JAN-97')
• NVL(job,'No Job Yet')
Using the NVL Function

SQL> SELECT ename, sal, comm, (sal*12)+NVL(comm,0)


2 FROM emp;

ENAME SAL COMM (SAL*12)+NVL(COMM,0)


---------- --------- --------- --------------------
KING 5000 60000
BLAKE 2850 34200
CLARK 2450 29400
JONES 2975 35700
MARTIN 1250 1400 16400
ALLEN 1600 300 19500
...
14 rows selected.
5.4.6 Nesting Functions

• Single-row functions can be nested to any


level.
• Nested functions are evaluated from deepest
level to the least-deep level.

F3(F2(F1(col,arg1),arg2),arg3)

Step 1 = Result 1
Step 2 = Result 2
Step 3 = Result 3
Nesting Functions

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
5.5 Group Functions
Group functions operate on sets of rows to
give one result 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
5.5.1 AVG Function
AVG([DISTINCT | ALL] n) Purpose: Returns the average
value of a column n.

•SELECT AVG(sal)
•FROM emp;

AVG(SAL)
----------
2161.6667
Group Functions and Null
Values
Group functions ignore null values in
the column.
SQL> SELECT AVG(comm)
2 FROM emp;

AVG(COMM)
---------
550
Using the NVL Function
with Group Functions
The NVL function forces group functions to
include null values.
SQL> SELECT AVG(NVL(comm,0))
2 FROM emp;

AVG(NVL(COMM,0))
----------------
157.14286
5.5.2 COUNT Function
•COUNT([* | [DISTINCT | ALL] expr}) Purpose: The number
of rows where expr evaluates to something other than null
(counts all selected rows using *, including duplicates and rows
with nulls.)

SELECT COUNT(empno)
FROM emp;

COUNT(EMPNO)
------------
15
Using the COUNT Function
COUNT(expr) returns the number of
nonnull rows.
SQL> SELECT COUNT(comm)
2 FROM emp
3 WHERE deptno = 30;

COUNT(COMM)
-----------
4
Using the COUNT Function
COUNT(*) returns the number of rows in
a table.
SQL> SELECT COUNT(*)
2 FROM emp
3 WHERE deptno = 30;

COUNT(*)
---------
6
5.5.3 MAX Function
MAX([DISTINCT | ALL] expr) Purpose: Returns the
maximum value of an expression specified by the
argument expr.

SELECT MAX(sal)
FROM emp;

MAX(SAL)
----------
5000
5.5.4 MIN Function
MIN([DISTINCT | ALL] expr) Purpose: Returns the
minimum value of an expression specified by the
argument expr.

SELECT MIN(sal)
FROM emp;

MIN(SAL)
----------
800
Using MIN and MAX Functions
You can use MIN and MAX for any
datatype.
SQL> SELECT MIN(hiredate), MAX(hiredate)
2 FROM emp;

MIN(HIRED MAX(HIRED
--------- ---------
17-DEC-80 12-JAN-83
5.5.5 STDDEV Function
STDDEV([DISTINCT|ALL] x) Purpose: Returns the
standard deviation of x, a number. SQL calculates the
standard deviation as the square root of the variance
defined for the VARIANCE group function.
SELECT STDDEV(sal)
FROM emp;

STDDEV(SAL)
----------
1189.087044
5.5.6 SUM Function
SUM([DISTINCT | ALL] n) Purpose: Returns the sum of
values of n.

SELECT SUM(sal)
FROM emp;

SUM(SAL)
----------
32425
5.5.7 VARIANCE Function
VARIANCE([DISTINCT|ALL] x) Purpose: Returns the
variance of x, a number. SQL calculates the variance of x using
the following formula: xi is one of the elements of x. n is the
number of elements in the set x. If n is 1, the variance is
defined as 0.
SELECT VARIANCE(sal)
FROM emp;

VARIANCE(SAL)
----------
1415791.67
5.6 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
20 3000 table 10 2916.6667
20 2975 for each 20 2175
30 1600 department” 30 1566.6667
30 2850
30 1250 1566.6667
30 950
30 1500
30 1250
Using Group Functions

SELECT [column,] group_function(column)


FROM table
[WHERE condition]
[GROUP BY column]
[ORDER BY column];
Creating Groups of Data:
GROUP 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.
Using the GROUP BY Clause
All columns in the SELECT list that are
not in group functions must be in the
GROUP BY clause.
SQL> SELECT deptno, AVG(sal)
2 FROM emp
3 GROUP BY deptno;

DEPTNO AVG(SAL)
--------- ---------
10 2916.6667
20 2175
30 1566.6667
Using the GROUP BY Clause
The GROUP BY column does not have
to be in the SELECT list.
SQL> SELECT AVG(sal)
2 FROM emp
3 GROUP BY deptno;

AVG(SAL)
---------
2916.6667
2175
1566.6667
5.7 GROUPS WITHIN THE
GROUPS
EMP
DEPTNO JOB SAL
--------- --------- ---------
10 MANAGER 2450
DEPTNO JOB SUM(SAL)
10 PRESIDENT 5000
-------- --------- ---------
10 CLERK 1300
10 CLERK 1300
20 CLERK 800 “sum salaries in 10 MANAGER 2450
20 CLERK 1100 the EMP table 10 PRESIDENT 5000
20 ANALYST 3000 for each job, 20 ANALYST 6000
20 ANALYST 3000 grouped by
20 CLERK 1900
20 MANAGER 2975 department”
20 MANAGER 2975
30 SALESMAN 1600
30 CLERK 950
30 MANAGER 2850
30 MANAGER 2850
30 SALESMAN 1250
30 SALESMAN 5600
30 CLERK 950
30 SALESMAN 1500
30 SALESMAN 1250
Using the GROUP BY Clause
on Multiple Columns
SQL> SELECT deptno, job, sum(sal)
2 FROM emp
3 GROUP BY deptno, job;

DEPTNO JOB SUM(SAL)


--------- --------- ---------
10 CLERK 1300
10 MANAGER 2450
10 PRESIDENT 5000
20 ANALYST 6000
20 CLERK 1900
...
9 rows selected.
Illegal Queries
Using Group Functions
Any column or expression in the SELECT
list that is not an aggregate function
must be in the GROUP BY clause.
SQL> SELECT deptno, COUNT(ename)
2 FROM emp;

SELECT deptno, COUNT(ename)


*
ERROR at line 1:
ORA-00937: not a single-group group function
Illegal Queries
Using Group Functions
• You cannot use the WHERE clause to restrict
groups.
• You use the HAVING clause to restrict groups.
SQL> SELECT deptno, AVG(sal)
2 FROM emp
3 WHERE AVG(sal) > 2000
4 GROUP BY deptno;

WHERE AVG(sal) > 2000


*
ERROR at line 3:
ORA-00934: group function is not allowed here
5.8 Excluding Group Results
EMP
DEPTNO SAL
--------- ---------
10 2450
10 5000 5000
10 1300
20 800
20 1100 “maximum DEPTNO MAX(SAL)
20 3000 salary --------- ---------
3000
20 3000 per department 10 5000
20 2975 greater than 20 3000
30 1600 $2900”
30 2850
30 1250
2850
30 950
30 1500
30 1250
5.8 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.
SELECT column, group_function
FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[HAVING group_condition]
[ORDER BY column];
Using the HAVING Clause

SQL> SELECT deptno, max(sal)


2 FROM emp
3 GROUP BY deptno
4 HAVING max(sal)>2900;

DEPTNO MAX(SAL)
--------- ---------
10 5000
20 3000
Using the HAVING Clause

SQL> SELECT job, SUM(sal) PAYROLL


2 FROM emp
3 WHERE job NOT LIKE 'SALES%'
4 GROUP BY job
5 HAVING SUM(sal)>5000
6 ORDER BY SUM(sal);

JOB PAYROLL
--------- ---------
ANALYST 6000
MANAGER 8275
Nesting Group Functions
Display the maximum average salary.

SQL> SELECT max(avg(sal))


2 FROM emp
3 GROUP BY deptno;

MAX(AVG(SAL))
-------------
2916.6667
Thank you

You might also like