Unit 3 - Function & Grouping,Joins and Set Operations in ORACLE
1. Working with table :
Function and Grouping
• Built in functions
• Grouping Data
• Joins
Dr R.Khanchana
Assistant Professor
Department of Computer Science
Sri Ramakrishna College of Arts and Science for
Women
2. • The built in function provides a powerful tool for enhancement of
a basic query.
• A function takes zero or more arguments and returns a single
value.
• Function are used for performing the calculation on data,
converting data modifying individual data ,manipulating a group
of rows, and formatting columns
There are two types they are
• Single row function
• Group function or Aggregate function
BUILT IN FUNCTIONS
3. Single Row Function
• The single row function take different types of argument, works on a
data item from each row and return one value for each row.
• The arguments are in the form of a constant value, variable name,
column,and/or expression.
• The value returned by a function may be a different type than the
argument supplied
Syntax
• Function(column |expression [,argument1,argument2,….])
4. There are various types of single row function
Character function : Take a character string or character type
column as an argument and return a character or numeric value.
Number function : Take a number or number type column as an
argument and return a numeric value
Datse function : Take date value or date type column as an argument
and return date type data.
Conversion function : Covert value from one data type to another
General function : Perform different task
Single Row Function - Types
5. Character function
Character function Use
UPPER(column | expr) Convert each letter to upper case
LOWER(column | expr) Convert each letter to lowercase
INITCAP(column | expr) Convert character value to the proper case
CONCAT(column | expr, (column | expr) Join the first value to the second value.
Similar to the || operator discussed earlier.
SUBSTR(column | expr,x,y) Return a substring, starting at character
position x, and return number of character
SUBSTR(column | expr,z) Return a substring, starting at character
position z and going to end of string
6. INSTR(column | expr ,c) Return the position of the supplied character
LTRIM(column | expr ,c) Removes the leading supplied character
RTRIM(column | expr ,c) Removes the trailing supplied character
TRIM(‘c’ FROM column | expr) Removes the leading and trailing character
TRIM(column) Removes the leading and trailing spaces
only
LENGTH(column | expr) Returns the number of character
LPAD(column | expr, n, ‘str’) Pad the value with ‘str’ to the left to a total
width of n.
RPAD(column | expr, N, ‘str’) Pad the value with ‘str’ to the right to a total
width of n.
REPLACE(column | expr, c,r) Replace substring c, if present in the column
or expression, with string r.
Character function
7. UPPER(‘Oracle’)->’ORACLE’
LOWER(‘DaTaBaSe SyStEmS’)->’database systems’
INITCAP(‘DaTaBaSe SyStEmS’)->’Database Systems’
SQL>SELECT UPPER(Lname),LOWER(Fname),
2 INITCAP(Fname || ‘’ || Lname)
3 FROM employee;
UPPER(LNAME) LOWER(FNAME) INITCAP(FNAME||”||LNAME)
----------------------------------------------------------------------------------------------------------
SMITH john John Smith
HOUSTON larry Larry Houston
ROBERTS alex Alex Robert
SHAW jinku Jinku Shaw
4 rows selected
SQL>
Character function in SELECT
8. SQL>SELECT Last, First FROM student
2 WHERE state=‘ny’
no rows selected
SQL>SELECT Last, First FROM student
2WHERE UPPER(State)=‘NY’;
LAST FIRST
----------------------------------
Tyler Mickey
Lee brian
SQL>
Character function in WHERE
9. SQL>SELECT Last, First FROM student
2 ORDER BY LENGTH(Last);
LAST FIRST
----------------------------------
Lee brian
Diaz Jose
Khan Amir
Tyler Mickey
Patel Rajesh
Rickles Deborah
6 rows selected
SQL>
Character function in ORDER BY
10. Character function in ORDER BY
• CONCAT (‘New’,’York’) ‘NewYork’
• SUBSTR(‘HEATER’,2,3) ‘EAT’
• INSTR(‘abcdefg’,d ) 4
• LTRIM(‘00022345’,’0’) ‘22345’
• RTRIM(‘0223455’,’5’) 02234
• TRIM(‘FROM’,’Monroe’) ‘Monroe’
• LENGTH(‘Oracle9i’) 8
• LPAD(265000,9,’$’) $$$265000
• RPAD(265000,9,’*’) 265000***
• REPLACE(‘Basketball’,’ket’,’e’ ) ‘Baseball’
11. NUMERIC FUNCTION
Numeric function use
ROUND(column|expr,[n]) Round the column or expression to n decimal places
TRUNC(column|expr,[n]) Truncates the column or expression to n decimal places
POWER(n,p) Returns n raised to power p(np)
ABS(n) Returns the absolute value of n
MOD(x,y) Returns the integer remainder of x/y.
SIGN(value) Returns 1 for positive ,-1 for negative and zero for a
zero
FLOOR(value) Returns the largest integer less than or equal to value
CEIL(value) Returns the smallest integer greater than or equal to
value
12. Round function
• The numeric function take numeric value(s) and return a numeric value
• The ROUND function rounds the value, expression,or column to n decimal
places
• If n is omitted, zero decimal place is assumed.
• If n is negative, rounding takes place to the left side of the decimal place
Example
ROUND(25.465,2)=25.47
ROUND(25.465,0)=25
ROUND(25.465,-1)=30
Numeric function
13. Truncate function
• The numeric function take numeric value(s) and return a numeric value
• If n is omitted, zero decimal place is assumed.
• If n is negative, truncation takes place to the left side of the decimal place
Example
TRUNC(25.465,2)=25.46
TRUNC(25.465,0)=25
TRUNC(25.465,-1)=20
Numeric function
14. The power function finds the power of a number(nP)
Example:
POWER(2,4)=16
POWER(5,3)=125
The ABS function returns the absolute value of a column ,expression,or value
ABS(-10)=10
The MOD function finds the integer remainder of x divided by y. It ignores the quotient.
MOD(5,2)=1
MOD(3,5)=3
MOD(8,4) = 0
Numeric Function
15. The sign function returns -1 for the negative number,1 for a positive number, and zero for a
zero
SGN(-50)=-1
SIGN(+43)=1
SIGN(0)=0
The floor function is similar to the TRUNC function ,and the ceil function is similar to the
round function. However ,both take one argument instead of two Example
FLOOR (54.7)=54
CEIL (54.7)=55
There is a difference in ceil function because it always returns the next higher integer value
Example
ROUND (54.3)=54
CEIL(54.3)=55
Numeric Function
16. NUMERIC FUNCTION -Example
• USING NUMERIC FUNCTION
• SQL>SELECT ROUND(5.55),1,TRUNC(5.5),SIGN(-5.5),MOD(5),2)
• 2 ABS(-5),POWER(3,4),FLOOR(5.5),CEIL(5.5)
• 3 FROM DUAL
ROUND(5.55),1 TRUNC(5.5) SIGN(-5.5) MOD(5),2)
ABS(-5) POWER(3,4) FLOOR(5.5) CEIL(5.5)
• -------------------------------------------------------------------------------------------
• 5.6 5 -1 1 81 5 6
17. • Oracle stores dates internally with day ,month, year,
century, hour, minute and second information
• He default data display format is DD-MON-YY
• There is a very useful date function called SYS DATE that
does not take any arguments
• SYS DATE returns the system current date
For example
SELECT SIS DATE FROM DUAL
DATE FUNCTION
18. SQL>DESCRIBE DUAL
Name Null? Type
------------------------------------------------------------------------------------------------
DUMMY VARCHAR2(1)
SQL>SELECT*FROM dual;
D
-
X
SQL>
SELECT TO_CHAR(SYSDATE,’DY,MONTH DD,YYYY HH:MI:SS P.M.’)
FROM DUAL;
• This query will display the current date you can get more information about day ,date and
time by using a format mask with SYSYDATE function.
DUAL TABLE
19. • Similarly the dual table can be used to display the outcome of any character and number
function or an arithmetic expression
• The Date-type column is very important .
• You can derive a lot of information from date columns by performing “date arithmetic”.
DATE ARITHMETIC
Date expression Result
Date+Number Adds a number of days to a date
Date-Number Subtract a number of days from a date
Date+Number/24 Adds a number of hours to a date
Date1-date2 Gives the number of days between two dates
DATE FUNCTION
20. Age calculation from birth date
SQL>SELECT Last,first(SYSDATE-birthdate)/365AGE
2 FROM student
LAST FIRST AGE
------------------------------------------------------------------------------------
Sri Sha 20.8289038
Tailor Mickey 19.0466573
Lie Corn 17.5363825
3 rows selected
SQL>
DATE FUNCTION
21. • The function MONTH _BETWEEN returns a number .
• If date1 is later than date2 the result is positive: otherwise the result is negative.
• The decimal part in the result is because of the portion of the month are extra days of the
month
• It is useful in finding the delay between the delivery date and payment date
Example MONTH-BETWEEN(‘02-DEC-03’,’04-APR-03’)->7.93548387
DATE FUNCTION
Date function use
MONTH-BETWEEN(Date1,Date2) Finds the number of months between two dates
ADD-MONTH(date,m) Adds calendar months to a date
NEXT-DATE(date,’day’) Finds the next assurance of a day from the given
date
LAST-DAY(date) Returns the last day of the month
ROUND(date[,’format’]) Rounds the date t the nearest day, month are year
22. • The function ADD-MONTH adds the number of months supplied as a second argument
ADD_MONTH(‘10-MAY-03’,3)->’10-AUG-03’
• The function NEXT-DAY returns the next Occurrence of the day the week following the
date supplied
NEXT_DAY(‘14-OCT-03’,’SUNDAY’)->19-OCT-03’
• The function LAST DAY finds the last date of the month for the day supplied as an
argument
LAST_DAY(‘05-FEB-04’)->’29-FEB-04’
DATE FUNCTION
23. Conversion Functions
Types
• Implicit Conversion
• Explicit Conversion
– Oracle provides three functions to covert from one data type to
another
Conversion Function Use
To_CHAR(number| date [,format]) Converts a number or a date to a VARCHAR2
value based on the format provided.
To_NUMBER( char [,format]) Converts a character value with valid digits to a
number using the format provided.
TO_DATE(char [,format]) Converts a character value to date value based
on the format provided. Default format is
DD-MON-YY.
24. Conversion Functions
1. To_CHAR ( number | date, [fmt], [nlsparams] )
The TO_CHAR function converts the number or date to
VARCHAR2 data type in the specified format (fmt). The
nlsparams parameter is used for number conversions. The
nlsparams specifies the following number format elements:
Decimal character
Group separator
Local currency symbol
International currency symbol
If the parameters are omitted, then it uses the default
formats specified in the session.
25. Conversion Functions
The Number format models are:
9: Specifies numeric position. The number
of 9's determine the display width.
0: Specifies leading zeros.
$: Floating dollar sign
.: Decimal position
,: Comma position in the number
2. TO_NUMBER( char, ['fmt'] )
The TO_NUMBER function converts the characters to a number format.
26. The Date format models are:
YYYY: Four digit representation of year
YEAR: Year spelled out
MM: Two digit value of month
MONTH: Full name of month
MON: Three letter representation of month
DY: Three letter representation of the day of the week
DAY: Full name of the day
DD: Numeric day of the month
fm: used to remove any padded blanks or leading zeros.
Conversion Functions
3. TO_DATE( char, ['fmt'] )
The TO_DATE function converts the characters to a date data type.
28. Other Functions – NVL Function
• The NVL function converts a null value to an
actual value supplied as an argument.
• The second argument is enclosed within the
single quotation marks for columns with DATE,
CHAR or VARCHAR2 datatypes.
• Syntax
– NVL(Column, value)
Example
NVL(Commission,0)
NVL(Hiredate, ‘01-JAN-03’)
NVL(PreReq,’None’)
29. Other Functions – NVL2 Function
• Extension of NVL function is the NVL2 function. It takes three
arguments instaed of two parameters used by NVL function.
• It checks for notnull and null values.
• If the column has a not null value, the second parameter is
displayed.
• If the column has a null value, the third parameter is
displayed.
• Syntax
– NVL2(Column, notnullvalue, nullvalue)
Example
NVL2 (PreReq,’YES’, ‘NO’))
30. Other Functions – COALESCE Function
• It is also an extension of NVL function.
• It specifies a single alternative for a null value,
whereas COALESCE function provides multiple
alternatives.
• Syntax
– COALESCE(column, alternative1, alternative2,…)
Example
– COALESCE(Commission, salary, -1)
– If the salary value is notnullvalue then it displays it.
– If the salary value is null , then display -1.
31. • It generates Null values.
• First it compares two expressions, then if their
values are equal, it generates null, or it returns
the first expression.
• Syntax
– NULLIF(exp1,exp2)
Example
– NULLIF(supervisor, 111)
– If the supervisor is equal to 111, then it null is
dispalyed. Otherwise the supervisor’s value is
displayed.
Other Functions – NULLIF Function
32. Other Functions – DECODE Function
• It is a conditional statement type of function.
• It tests a column or expression and for each of its matching
value, provides an action.
• Syntax
– DECODE(column|expr, value1, action1,
[value2,action2,…]
[,default]);
Example
SELECT Lnname, salary,
DECODE(Positioid, 1, salary*1.2,
2, salary *1.15,
3, salary*1.1,
4, salary *1.05,
salary) New Salary”
FROM employee;
33. GROUPING DATA
• The GROUP BY clause is used in
a SELECT statement to group rows into a set of
summary rows by values of columns or
expressions. The GROUP BY clause returns one
row per group.
• The GROUP BY clause is often used
with aggregate functions such
as AVG(), COUNT(), MAX(), MIN() and SUM()
34. Group By functions
• Syntax
SELECT Column, groupfunction(column)
FROM tablename
[WHERE condition(s)]
[GROUP BY column| expression]
[ORDER BY column | expression [ASC|DESC]]);
35. SUM(): Returns the sum or total of each group.
COUNT(): Returns the number of rows of each group.
AVG(): Returns the average and mean of each group.
MIN(): Returns the minimum value of each group.
MAX(): Returns the minimum value of each group.
Aggregate functions
42. HAVING Clause
• The HAVING clause is an optional clause of
the SELECT statement.
• It is used to filter groups of rows returned by
the GROUP BY clause.
• This is why the HAVING clause is usually used
with the GROUP BY clause.
53. Joins
• A JOIN clause is used to combine rows from two or more tables,
based on a related column between them.
• The join condition combines a row in one table with a row in
another table based in the same values in the common column.
• Cartesian Product
– Cartesian product results from a multiple table query that does not have a
WHERE clause.
58. 1.Equijoin
⚫ The Equijoin is a join with a join condition
involving common columns from two tables.
Syntax:
SELECT Columnnames
FROM tablename
WHERE join condition(s);
⚫ The join key not always include a foreign key
column from one table and the referenced
primary key column from the other table
59. Table Aliases
⚫ Table aliases are used to avoid using lengthy table names
over and over again in a query
⚫ A table aliases can be from 1 to 30 characters long
⚫ very short alias name are used to shorten the query and save
some keystrokes
⚫ The table aliases names are used to shorten the query and
save some keystrokes
⚫ The table name is written followed by space and the alias is
supplied
⚫ All table aliases are valid only i the SELECT query,when
they name are used
60. Table Aliases
⚫ Table aliases are used to avoid using lengthy table names
over and over again in a query
⚫ A table aliases can be from 1 to 30 characters long
⚫ very short alias name are used to shorten the query and save
some keystrokes
⚫ The table aliases names are used to shorten the query and
save some keystrokes
⚫ The table name is written followed by space and the alias is
supplied
⚫ All table aliases are valid only i the SELECT query,when
they name are used
62. Table Aliases –Example
SQL> SELECT e.Lname ||‘,’e.Fname EMPLOYEE,
2 d.Deptname DEPARTMENT, q.QualDesc QUALIFICATION
3 FROM employee e,dept d,qualification q
4 WHERE e.DeptId = d.DeptId
5 AND employee.PositionId =position.PositionId;
EMPLOYEE DEPARTMENT QUALIFICATION
smith,john Finance Doctorate
Houston,Larry Marketing Masters
Roberts,Sandi Finance Masters
McCall,Alex Infosys Associate
Dev,Derek Infosys Doctorate
Garner,Stanley sales High School
Chen,Sunny Finance Bachelors
8 rows are selected.
SQL>
63. 1.Equijoin
SQL>SELECT student.Last ||’,’|| student.First STUDENT,
2 faculty.Name FACULTY, faculty.Phone TEL
3 FROM student, faculty
4 WHERE student.Faculty=faculty.FacultyId
5/
Student FACULTY TEL
Diaz,Jose Mobley 529
Tyler,Mickey Chang 587
Patel,Rajesh Jones 525
Rickles,Deborah Chang 587
Lee,Brian sen 579
Khan,Amir williams 533
Equijoin
The cartesian product as mentioned earlier is rarely useful, but equijoin is very
important operation in database querying
65. Multiple Joins
SQL> SELECT employee.Lname ||‘,’ employee.Fname EMPLOYEE,
2 dept.Deptname DEPARTMENT, position.PosDesc POSITION
3 FROM employee,dept,position
4 WHERE employee.DeptId = dept.DeptId
5 AND employee.PositionId =position.PositionId;
EMPLOYEE DEPARTMENT POSITION
smith,john Finance President
Houston,Larry Marketing Manager
Roberts,Sandi Finance Manager
McCall,Alex Infosys Programmer
Dev,Derek Infosys Manager
Shaw,Jinku sales Manager
Garner,Stanley sales Manager
Chen,Sunny Finance Accountant
8 rows are selected.
SQL>
66. 2. Nonequijoin
Additional conditions:
Additional condition like AND operator restrict the information
Nonequijoin:
⚫ There is no matching column in the EMPLEVEL table for
the salary column in the EMPLOYEE table
⚫ The only relationship between the two tables is between two
tables is between the salary column of the EMPLOYEE table
The nonequijoin condition:
e.Salary>=L.LowSalary AND e.Salary<=I.HighSalary;
67. Additional Condition with join
SQL>SELECT e.Fname EMPLOYEE
2 d.DeptName DEPARTMENTNAME,q.QualDesc QUALIFICATION
3 p.PostDesc POSITION
4 FROM employee e,dept d,qualification q,
position p,
5 WHERE e.DeptId = d.DeptId
6 AND e.QualId =d.QualId
7 AND e.Position = p.PositionId
8 AND e.DeptId =p.PositionId AND e.DeptId = 10;
9/
EMPLOYEE DEPARTMENT QUALIFICATION POSITION
Smith,John Finance Doctorate president
Roberts,Sandi Finance Masters Manger
Chen,Sunny Finance Bachelors Accountant
SQL>
69. 3. Outerjoin
⚫ A row in one table does not have a matching values in the other table,it is not
joined
⚫ The table that does not contain the matching value is known as the deficient
table
⚫ The general syntax is :
SELECT tablename1.columnname,tablename2.columnname
FROM tablename1,tablename2
WHERE tablename1.columnname(+)= tablename2.columnname
⚫ The join condition will look different if the (+)operator is used on the right side
EX: WHERE tablename1.columnname= tablename2.columnname(+)
⚫ Next example (+) is used on the QUALIFICATION side,because it is a deficient
table or it generates a null value for the row(s) in the EMPLOYEE table without
any qualification table.
70. 3. Outerjoin - Example
SQL> SELECT e.Fname ||‘,’||e.Lname EMPLOYEE,q.QualDesc
2 FROM employee e, qualification q
3 WHERE e.Qualid =q.Qualid(+)
4/
EMPLOYEE QUALDESC
John Smith Doctorate
Larry Houston Masters
Sandi Roberts Masters
Alex McCall Associate
Derek Dev Doctorate
Jinku Shaw
Stanley Garner High School
Sunny Chen Bachelors
8 rows selected
SQL>
72. Self join
⚫ A self joining table to itself
⚫ A self join is one join that is not easy to understand
⚫ The following operations are performed in the self-join
*Two copies of the EMPLOYEE table are created with the
aliases e and s.
*An employee’s last name is picked from the e table,and
the corresponding Supervisor ID is retrieved
*The matching EmployeeId is found from the table .The
first employee in the e table does not have a supervisor and so is
not picked
* The last name from the s table is retrived based on the
employeeId
81. Set Operators
• An Independent queries.
•It is used to reconcile the results of the two queries
into a single result set.
•These operations are based upon principles in an
operator appears between two elementary mathematical
set theory. The general syntax is
SELECT-Query1
Set operator
SELECT-Query2
82. Types of Set Operators
● MINUS is used to produce the
difference between two result
sets.
● INTERSECT is used to show
the commonalities between two
result sets.
● UNION combines two results
sets, but removes any
duplicates.
● UNION ALL combines two
results sets, but preserves any
duplicates.
84. Union
The UNION operator takes output from two queries and return all rows from
both results
The duplicate rows are displayed only once
If you perform union on two tables use WHERE clause to filter rows
85. Union All
The UNION ALL operation is similar to the UNION operation.
The difference is it also displays duplicate rows
87. MINUS
The operation is same as difference operation
When MINUS is performed on Outputs from two queriess, the result is the rows
in the first query’s result that are not in the second query result