Professional Documents
Culture Documents
CHAPTER 5 (Slides) PDF
CHAPTER 5 (Slides) PDF
SQL Functions
Objectives
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
Character
General Number
Single-row
functions
Conversion Date
5.4.1 Character Functions
Character
functions
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.
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.
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 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
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.
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.
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
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.
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 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 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.
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
• 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
NUMBER VARCHAR2
DATE VARCHAR2
Implicit Datatype Conversion
TO_CHAR TO_CHAR
5.4.4.1 TO_CHAR Function
TO_CHAR(date, 'fmt')
TO_CHAR(SYSDATE,'DD,MONTH,YEARHH:MI:SS')
------------------------------------------
31,AUGUST ,TWO THOUSAND EIGHT 06:44:58
Elements of Date Format Model
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')
SELECT TO_NUMBER('1234') + 66
FROM DUAL;
TO_NUMBER('1234')+66
--------------------
1300
5.4.5.1 DECODE Function
F3(F2(F1(col,arg1),arg2),arg3)
Step 1 = Result 1
Step 2 = Result 2
Step 3 = Result 3
Nesting Functions
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
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 MAX(SAL)
--------- ---------
10 5000
20 3000
Using the HAVING Clause
JOB PAYROLL
--------- ---------
ANALYST 6000
MANAGER 8275
Nesting Group Functions
Display the maximum average salary.
MAX(AVG(SAL))
-------------
2916.6667
Thank you