Chapter 6 Functions
Oracle 12c
Database
Copyright @Jamhuriya University 01/24/2022 1
Chapter 6 Functions
Using Single-Row
And Aggregate
Functions
Copyright @Jamhuriya University 01/24/2022 2
Functions
Functions are programs that take zero or more arguments and return a single value.
Oracle has built a number of functions into SQL, and these functions can be called from SQL
statements.
Single-row functions operate on expressions derived from columns or literals, and they are executed
once for each row retrieved.
Functions are a very powerful feature of SQL. They can be used to do the following:
Perform calculations on data
Modify individual data items
Manipulate output for groups of rows
Format dates and numbers for display
Convert column data types
SQL functions sometimes take arguments and always return a value.
Copyright @Jamhuriya University 01/24/2022 3
Function Classifications
The functions can be classified into many groups:
Single-row functions
Aggregate functions (also known as group functions)
Analytical functions and regular expression functions
National-language functions
Object-reference functions
Programmer-defined functions
Copyright @Jamhuriya University 01/24/2022 4
Types of Functions
• There are two types of functions:
Single-row functions
Multiple-row functions
Copyright @Jamhuriya University 01/24/2022 5
Single-Row Functions
These functions operate on single rows only and return one result per row.
Manipulate data items
Accept arguments and return one value
Act on each row that is returned
Return one result per row
May modify the data type
Can be nested
Accept arguments that can be a column or an expression
Copyright @Jamhuriya University 01/24/2022 6
Types of single-row functions
There are different types of single-row functions. This lesson covers the following ones:
Copyright @Jamhuriya University 01/24/2022 7
Types of single-row functions
• Character functions: Accept character input and can return both character and number values
• Number functions: Accept numeric input and return numeric values
• Date functions: Operate on values of the DATE data type (All date functions return a value of the DATE data type except
the MONTHS_BETWEEN function, which returns a number.)
• Conversion functions: Convert a value from one data type to another datatype
• General functions:
• NVL
• NVL2
• NULLIF
• COALESCE
• CASE
• DECODE
Copyright @Jamhuriya University 01/24/2022 8
Character Functions
• Single-row character functions accept character data as input and can return both character and
numeric values.
• Character functions can be divided into the following:
Case-conversion functions
Character-manipulation functions
Copyright @Jamhuriya University 01/24/2022 9
Case-Conversion Functions
• These functions convert the case for character strings:
LOWER: Converts mixed-case or uppercase character strings to lowercase
UPPER: Converts mixed-case or lowercase character strings to uppercase
INITCAP: Converts the first letter of each word to uppercase and the remaining
letters to lowercase
Function Result
LOWER('SQL Course') sql course
UPPER('SQL Course') SQL COURSE
INITCAP('SQL Course') Sql Course
Copyright @Jamhuriya University 01/24/2022 10
Character-manipulation functions
• These functions manipulate character strings:
Function Result
CONCAT('Hello', 'World') HelloWorld
SUBSTR('HelloWorld',1,5) Hello
LENGTH('HelloWorld') 10
INSTR('HelloWorld', 'W') 6
LPAD(salary,10,'*') *****24000
RPAD(salary, 10, '*') 24000*****
REPLACE('JACK and JUE','J','BL') BLACK and BLUE
TRIM('H' FROM 'HelloWorld') elloWorld
Copyright @Jamhuriya University 01/24/2022 11
Using the Character-Manipulation Functions
1
SELECT employee_id, CONCAT(first_name, last_name) NAME,
job_id, LENGTH (last_name), 2
INSTR(last_name, 'a') "Contains 'a'?"
FROM employees
3
WHERE SUBSTR(job_id, 4) = 'REP';
1 2 3
Copyright @Jamhuriya University 01/24/2022 12
Number Functions
Number functions accept numeric input and return numeric values
ROUND: Rounds value to a specified decimal
TRUNC: Truncates value to a specified decimal
MOD: Returns remainder of division
Function Result
ROUND(45.926, 2) 45.93
TRUNC(45.926, 2) 45.92
MOD(1600, 300) 100
Copyright @Jamhuriya University 01/24/2022 13
Using the ROUND Function
DUAL is a dummy table that you can use to view results from functions and calculations and owned by
the user SYS and can be accessed by all users.
1 2
SELECT ROUND(45.923,2), ROUND(45.923,0),
ROUND(45.923,-1) 3
FROM DUAL;
1 2 3
Copyright @Jamhuriya University 01/24/2022 14
Using the TRUNC Function
• The TRUNC function truncates the column, expression, or value to n decimal places.
• The TRUNC function works with arguments similar to those of the ROUND function.
1 2
SELECT TRUNC(45.923,2), TRUNC(45.923),
TRUNC(45.923,-1) 3
FROM DUAL;
1 2 3
Copyright @Jamhuriya University 01/24/2022 15
Using the MOD Function
• The MOD function finds the remainder of the first argument divided by the second argument.
SELECT last_name, salary, MOD(salary, 5000)
FROM employees
WHERE job_id = 'SA_REP';
Copyright @Jamhuriya University 01/24/2022 16
Working with Dates
• The Oracle database stores dates in an internal numeric format: century,
year, month, day, hours, minutes, and seconds.
• The default date display format is DD-MON-RR.
Enables you to store 21st-century dates in the 20th century by specifying only
the last two digits of the year
Enables you to store 20th-century dates in the 21st century in the same way
Copyright @Jamhuriya University 01/24/2022 17
Working with Dates
SELECT last_name, hire_date
FROM employees
WHERE hire_date < '01-FEB-88';
RR Date Format
CurrentYear
Current Year Specified Date RR Format YY Format
1995 27-OCT-95 1995 1995
1995 27-OCT-17 2017 1917
2001 27-OCT-17 2017 2017
2001 27-OCT-95 1995 2095
Copyright @Jamhuriya University 01/24/2022 18
Working with Dates
CurrentYear
Current Year Specified Date RR Format YY Format
1995 27-OCT-95 1995 1995
1995 27-OCT-17 2017 1917
2001 27-OCT-17 2017 2017
2001 27-OCT-95 1995 2095
If the specified two-digit year is:
0–49 50–99
If two digits The return date is in The return date is in
of the 0–49 the current century the century before
current the current one
year are: The return date is The return date is in
50–99 in the century after the current century
the current one
Copyright @Jamhuriya University 01/24/2022 19
Using the SYSDATE Function
• SYSDATE is a date function that returns the current database server date and time.
• You can use SYSDATE just as you would use any other column name. SELECT sysdate
FROM dual;
• 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.
SELECT last_name, (SYSDATE-hire_date)/7 AS WEEKS
FROM employees
WHERE department_id = 90;
Copyright @Jamhuriya University 01/24/2022 20
Date-Manipulation Functions
Function Result
MONTHS_BETWEEN Number of months between two dates
ADD_MONTHS Add calendar months to date
NEXT_DAY Next day of the date specified
LAST_DAY Last day of the month
ROUND Round date
TRUNC Truncate date
The above list is a subset of the available date functions.
ROUND and TRUNC number functions can also be used to manipulate the date values
Copyright @Jamhuriya University 01/24/2022 21
Date-Manipulation Functions
• Date functions operate on Oracle dates. All date functions return a value of the DATE data type except
MONTHS_BETWEEN, which returns a numeric value.
MONTHS_BETWEEN(date1, date2): Finds the number of months between date1 and date2. The result can
be positive or negative.
ADD_MONTHS(date, n): Adds n number of calendar months to date. The value of n must be an integer
and can be negative.
NEXT_DAY(date, 'char'): Finds the date of the next specified day of the week (' char') following date. The
value of char may be a number representing a day or a character string.
LAST_DAY(date): Finds the date of the last day of the month that contains date.
Copyright @Jamhuriya University 01/24/2022 22
Date-Manipulation Functions
SELECT employee_id, hire_date, MONTHS_BETWEEN (SYSDATE, hire_date) TENURE,
ADD_MONTHS (hire_date, 6) REVIEW,
NEXT_DAY (hire_date, 'FRIDAY’),
LAST_DAY(hire_date)
FROM employees
WHERE MONTHS_BETWEEN (SYSDATE, hire_date) < 100;
Function Result
MONTHS_BETWEEN('01-SEP-95','11-JAN-94') 19.6774194
ADD_MONTHS (‘31-JAN-96',1) ‘29-FEB-96'
NEXT_DAY ('01-SEP-95','FRIDAY') '08-SEP-95'
LAST_DAY ('01-FEB-95') '28-FEB-95'
Copyright @Jamhuriya University 01/24/2022 23
Using ROUND and TRUNC Functions with
Dates
• Assume SYSDATE = '25-JUL-03’:
Function Result
ROUND(SYSDATE,'MONTH') 01-AUG-03
ROUND(SYSDATE ,'YEAR') 01-JAN-04
TRUNC(SYSDATE ,'MONTH') 01-JUL-03
TRUNC(SYSDATE ,'YEAR') 01-JAN-03
Copyright @Jamhuriya University 01/24/2022 24
What Are Group Functions?
Group functions, also called multiple-row functions, return one result per group of rows
processed. Group functions operate on sets of rows to give one result per group.
EMPLOYEES
Maximum salary in
EMPLOYEES table
Copyright @Jamhuriya University 01/24/2022 25
Types of Group Functions
Because these functions return only one result per group of data, they’re also known as aggregate
functions.
AVG
COUNT
MAX
MIN Group
functions
STDDEV
SUM
VARIANCE
SELECT group_function(column), ...
FROM table
[WHERE condition]
[ORDER BY column];
Copyright @Jamhuriya University 01/24/2022 26
Guidelines for using the group functions:
The group function is placed after the SELECT keyword.
You may have multiple group functions separated by commas.
DISTINCT makes the function consider only nonduplicate values; ALL makes it
consider every value, including duplicates.
The default is ALL and therefore does not need to be specified.
The data types for the functions with an expr argument may be CHAR, VARCHAR2,
NUMBER, or DATE.
All group functions ignore null values.
To substitute a value for null values, use the NVL, NVL2, or COALESCE functions.
Copyright @Jamhuriya University 01/24/2022 27
Using Aggregate Functions
You can use AVG and SUM for numeric data but you can use MIN
and MAX for numeric, character, and date data types.
SELECT AVG(salary), MAX(salary),MIN(salary),SUM(salary)
FROM employees
WHERE job_id LIKE '%REP%';
SELECT MIN(hire_date), MAX(hire_date)
FROM employees;
Copyright @Jamhuriya University 01/24/2022 28
Using the COUNT Function
COUNT(*) returns the number of rows in a table:
SELECT COUNT(*)
1 FROM employees
WHERE department_id = 50;
COUNT(expr) returns the number of rows with
non-null values for expr:
SELECT COUNT(commission_pct)
2 FROM employees
WHERE department_id = 80;
Copyright @Jamhuriya University 01/24/2022 29
Using the DISTINCT Keyword
COUNT(DISTINCT expr) returns the number of distinct non-null values of expr.
To display the number of distinct department values in the EMPLOYEES table:
SELECT COUNT(DISTINCT department_id)
FROM employees;
Copyright @Jamhuriya University 01/24/2022 30
Group Functions and Null Values
Group functions ignore null values in the column:
SELECT AVG(commission_pct)
1 FROM employees;
The NVL function forces group functions to include null values:
SELECT AVG(NVL(commission_pct, 0))
2 FROM employees;
Copyright @Jamhuriya University 01/24/2022 31
Creating Groups of Data
EMPLOYEES
Until this point in our discussion,
4400
Average salary in
all group functions have treated 9500
EMPLOYEES table for
each department
the table as one large group of
3500
information. At times, however,
you need to divide the table of 6400
information into smaller groups.
10033
This can be done by using the
…
GROUP BY clause.
Copyright @Jamhuriya University 01/24/2022 32
Guidelines of Grouping
If you include a group function in a SELECT clause, you cannot select individual
results as well, unless the individual column appears in the GROUP BY clause.
You receive an error message if you fail to include the column list in the GROUP BY
clause.
Using a WHERE clause, you can exclude rows before dividing them into groups.
You must include the columns in the GROUP BY clause.
You cannot use a column alias in the GROUP BY clause.
Copyright @Jamhuriya University 01/24/2022 33
Using the GROUP BY Clause
You can divide rows in a table into smaller groups by using the GROUP BY clause.
SELECT column, group_function(column)
FROM table
[WHERE condition]
[GROUP BY group_by_expression]
[ORDER BY column];
All columns in the SELECT list that are not in group functions must be in the GROUP BY
clause.
SELECT department_id, AVG(salary)
FROM employees
GROUP BY department_id ;
Copyright @Jamhuriya University 01/24/2022 34
Grouping by More than One Column
EMPLOYEES Add the salaries in the EMPLOYEES
table for each job, grouped by
department.
Copyright @Jamhuriya University 01/24/2022 35
Grouping by More than One Column
You can return summary results for groups and subgroups by listing more than one GROUP BY column.
You can determine the default sort order of the results by the order of the columns in the GROUP BY clause.
SELECT department_id dept_id, job_id, SUM(salary)
FROM employees
GROUP BY department_id, job_id
ORDER BY department_id;
Copyright @Jamhuriya University 01/24/2022 36
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: SELECT department_id, COUNT(last_name)
FROM employees;
A GROUP BY clause must be added to
count the last names for each
department_id.
SELECT department_id, job_id, COUNT(last_name)
FROM employees
GROUP BY department_id;
Either add job_id in the GROUP BY or
remove the job_id column from the
SELECT list.
Copyright @Jamhuriya University 01/24/2022 37
Illegal Queries Using Group Functions
You cannot use the WHERE clause to restrict groups. You use the HAVING clause to restrict groups.
You cannot use group functions in the WHERE clause.
SELECT department_id, AVG(salary)
FROM employees
WHERE AVG(salary) > 8000
GROUP BY department_id;
Cannot use the
WHERE clause to
restrict groups
Copyright @Jamhuriya University 01/24/2022 38
Restricting Group Results
EMPLOYEES
The HAVING clause is used to restrict
the groups returned by a query. If you
need to use a group function to restrict The maximum salary per
department when it is
groups, you must use the HAVING greater than $10,000
clause because the WHERE clause
can’t contain group functions. Although
the WHERE clause restricts the records
the query processes, the HAVING
clause specifies which groups are …
displayed in the results.
Copyright @Jamhuriya University 01/24/2022 39
Restricting Group Results with the
HAVING Clause
When you use the HAVING clause, the Oracle server restricts groups as follows:
1. Rows are grouped.
2. The group function is applied.
3. 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];
Copyright @Jamhuriya University 01/24/2022 40
Using the HAVING Clause
SELECT department_id, MAX(salary)
FROM employees
GROUP BY department_id
HAVING MAX(salary)>10000 ;
SELECT job_id, SUM(salary) PAYROLL
FROM employees
WHERE job_id NOT LIKE '%REP%'
GROUP BY job_id
HAVING SUM(salary) > 13000
ORDER BY SUM(salary);
SELECT MAX(AVG(salary))
Nesting Group FROM employees
Functions: GROUP BY department_id;
Copyright @Jamhuriya University 01/24/2022 41
THANK YOU