0% found this document useful (0 votes)
7 views42 pages

Oracle 12c Chapter 4

Chapter 4 of the Oracle 12c Database discusses the use of single-row and aggregate functions in SQL, explaining their classifications and types. It details various single-row functions, including character, number, and date functions, as well as group functions that return results per group of rows. The chapter also covers guidelines for using these functions, including the GROUP BY and HAVING clauses for organizing and filtering data.

Uploaded by

maanxidig69
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views42 pages

Oracle 12c Chapter 4

Chapter 4 of the Oracle 12c Database discusses the use of single-row and aggregate functions in SQL, explaining their classifications and types. It details various single-row functions, including character, number, and date functions, as well as group functions that return results per group of rows. The chapter also covers guidelines for using these functions, including the GROUP BY and HAVING clauses for organizing and filtering data.

Uploaded by

maanxidig69
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 42

Chapter 4 Functions

Oracle 12c
Database
Chapter 4 Functions

Using Single-Row
And Aggregate
Functions
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.
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
Types of Functions

• There are two types of functions:

 Single-row functions

 Multiple-row functions
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
Types of single-row functions
There are different types of single-row functions. This lesson covers the following

ones:
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
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
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
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


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
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
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
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
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';
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
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
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
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;
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
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.
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'
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
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


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];
Guidelines for using the group
Thefunctions:
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.
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;
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;
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;
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;
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.
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.


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 ;
Grouping by More than One
Column
EMPLOYEES Add the salaries in the EMPLOYEES
table for each job, grouped by
department.


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
SELECT sort order of the
department_id results by
dept_id, the order
job_id, of the columns in the
SUM(salary)
GROUP BY clause.FROM employees
GROUP BY department_id, job_id
ORDER BY department_id;
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.
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
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.


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];
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;
THANK YOU

You might also like