SlideShare a Scribd company logo
1 of 88
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
• 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
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,….])
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
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
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
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
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
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
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’
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
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
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
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
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
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
• 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
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
• 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
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
• 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
• 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
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.
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.
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.
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.
Conversion Functions -Examples
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’)
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’))
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.
• 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
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;
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()
Group By functions
• Syntax
SELECT Column, groupfunction(column)
FROM tablename
[WHERE condition(s)]
[GROUP BY column| expression]
[ORDER BY column | expression [ASC|DESC]]);
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
SUM Function
AVG Function
COUNT Function
MIN Function
MAX Function
Quiz
• https://quizizz.com/admin/quiz/5f47369049d
984001b6ea4d0
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.
HAVING Clause
GROUP BY Clause - Examples
HAVING Clause -Examples
HAVING Clause – Examples
Difference between WHERE and
HAVING Clause
Nesting Group Functions
Quiz
• https://quizizz.com/admin/quiz/5f4cb8204ca1
56001b50e8f0
Joins & Set
Operations
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.
Types of Joins
1. Equijoin
Syntax
• SELECT Columnnames FROM tablenames
WHERE join condition(s);
JOIN CONDITIONS
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
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
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
Table Alias - Example
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>
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
1.Equijoin -Example
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>
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;
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>
2. Nonequijoin -Examples
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.
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>
4. SELF JOIN
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
Self join
SQL> SELECT e.Lname ||’,’|| e.Fname Employee
2 s.Lname ||’,’|| s.Fname Manager
3 FROM employee e,employee s
4 WHERE e.supervisor =s.EmployeeId
EMPLOYEE MANAGER
Houston,Larry Smith,John
Roberts,Sandi Smith,John
McCall,Alex Dev,Derek
Dev,Derek Smith,John
Shaw,Jinku Garner,Stanley
Garner,Stanley Smith,John
Chen,Sunny Roberts,Sandi
7 rows selected
SQL>
STUDENT
FACULTY
EMPLOYEE
QUALIFICATION
DEPARTMENT (1)
DEPARTMENT(2)
POSITION
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
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.
Input Tables
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
Union All
 The UNION ALL operation is similar to the UNION operation.
 The difference is it also displays duplicate rows
INTERSECT
The intersection operation works on output from two
separate queries and returns rows that appear in both
outputs.
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
Quiz
• https://quizizz.com/admin/quiz/5f5869a9e88
39e001ec42eab

More Related Content

What's hot (20)

SQL Queries Information
SQL Queries InformationSQL Queries Information
SQL Queries Information
 
Types Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql ServerTypes Of Join In Sql Server - Join With Example In Sql Server
Types Of Join In Sql Server - Join With Example In Sql Server
 
Sql tutorial
Sql tutorialSql tutorial
Sql tutorial
 
Advanced Sql Training
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Training
 
Database constraints
Database constraintsDatabase constraints
Database constraints
 
set operators.pptx
set operators.pptxset operators.pptx
set operators.pptx
 
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with ExamplesDML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
 
Integrity Constraints
Integrity ConstraintsIntegrity Constraints
Integrity Constraints
 
Procedure and Functions in pl/sql
Procedure and Functions in pl/sqlProcedure and Functions in pl/sql
Procedure and Functions in pl/sql
 
Oraclesql
OraclesqlOraclesql
Oraclesql
 
Sql Constraints
Sql ConstraintsSql Constraints
Sql Constraints
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functions
 
SQL: Structured Query Language
SQL: Structured Query LanguageSQL: Structured Query Language
SQL: Structured Query Language
 
PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts
 
1 - Introduction to PL/SQL
1 - Introduction to PL/SQL1 - Introduction to PL/SQL
1 - Introduction to PL/SQL
 
Index in sql server
Index in sql serverIndex in sql server
Index in sql server
 
Advanced sql
Advanced sqlAdvanced sql
Advanced sql
 
SQL Views
SQL ViewsSQL Views
SQL Views
 
SQL commands
SQL commandsSQL commands
SQL commands
 
Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)Les01 (retrieving data using the sql select statement)
Les01 (retrieving data using the sql select statement)
 

Similar to Unit 3 - Function & Grouping,Joins and Set Operations in ORACLE

Oracle sql functions
Oracle sql functionsOracle sql functions
Oracle sql functionsVivek Singh
 
SQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTIONSQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTIONArun Sial
 
2 sql - single-row functions
2   sql - single-row functions2   sql - single-row functions
2 sql - single-row functionsAnkit Dubey
 
Key functions in_oracle_sql
Key functions in_oracle_sqlKey functions in_oracle_sql
Key functions in_oracle_sqlpgolhar
 
Introduction to oracle functions
Introduction to oracle functionsIntroduction to oracle functions
Introduction to oracle functionsNitesh Singh
 
COIS 420 - Practice 03
COIS 420 - Practice 03COIS 420 - Practice 03
COIS 420 - Practice 03Angel G Diaz
 
Intro to tsql unit 10
Intro to tsql   unit 10Intro to tsql   unit 10
Intro to tsql unit 10Syed Asrarali
 
SQL WORKSHOP::Lecture 3
SQL WORKSHOP::Lecture 3SQL WORKSHOP::Lecture 3
SQL WORKSHOP::Lecture 3Umair Amjad
 
sql functions3 (1).pdf
sql functions3 (1).pdfsql functions3 (1).pdf
sql functions3 (1).pdfUsha570012
 
Python High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.pptPython High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.pptAnishaJ7
 
Using single row functions to customize output
Using single row functions to customize outputUsing single row functions to customize output
Using single row functions to customize outputSyed Zaid Irshad
 
Hive function-cheat-sheet
Hive function-cheat-sheetHive function-cheat-sheet
Hive function-cheat-sheetDr. Volkan OBAN
 
Database Query Using SQL_ip.docx
Database Query Using SQL_ip.docxDatabase Query Using SQL_ip.docx
Database Query Using SQL_ip.docxVandanaGoyal21
 
Introduction to Data Science With R Lab Record
Introduction to Data Science With R Lab RecordIntroduction to Data Science With R Lab Record
Introduction to Data Science With R Lab RecordLakshmi Sarvani Videla
 
Les03 (Using Single Row Functions To Customize Output)
Les03 (Using Single Row Functions To Customize Output)Les03 (Using Single Row Functions To Customize Output)
Les03 (Using Single Row Functions To Customize Output)Achmad Solichin
 

Similar to Unit 3 - Function & Grouping,Joins and Set Operations in ORACLE (20)

Oracle sql functions
Oracle sql functionsOracle sql functions
Oracle sql functions
 
Oracle sql ppt2
Oracle sql ppt2Oracle sql ppt2
Oracle sql ppt2
 
SQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTIONSQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTION
 
2 sql - single-row functions
2   sql - single-row functions2   sql - single-row functions
2 sql - single-row functions
 
Key functions in_oracle_sql
Key functions in_oracle_sqlKey functions in_oracle_sql
Key functions in_oracle_sql
 
Introduction to oracle functions
Introduction to oracle functionsIntroduction to oracle functions
Introduction to oracle functions
 
Introduction to Oracle Functions--(SQL)--Abhishek Sharma
Introduction to Oracle Functions--(SQL)--Abhishek SharmaIntroduction to Oracle Functions--(SQL)--Abhishek Sharma
Introduction to Oracle Functions--(SQL)--Abhishek Sharma
 
COIS 420 - Practice 03
COIS 420 - Practice 03COIS 420 - Practice 03
COIS 420 - Practice 03
 
Intro to tsql unit 10
Intro to tsql   unit 10Intro to tsql   unit 10
Intro to tsql unit 10
 
SQL WORKSHOP::Lecture 3
SQL WORKSHOP::Lecture 3SQL WORKSHOP::Lecture 3
SQL WORKSHOP::Lecture 3
 
Les03
Les03Les03
Les03
 
Tableau functions
Tableau   functionsTableau   functions
Tableau functions
 
sql functions3 (1).pdf
sql functions3 (1).pdfsql functions3 (1).pdf
sql functions3 (1).pdf
 
Python High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.pptPython High Level Functions_Ch 11.ppt
Python High Level Functions_Ch 11.ppt
 
Bcsl 033 solve assignment
Bcsl 033 solve assignmentBcsl 033 solve assignment
Bcsl 033 solve assignment
 
Using single row functions to customize output
Using single row functions to customize outputUsing single row functions to customize output
Using single row functions to customize output
 
Hive function-cheat-sheet
Hive function-cheat-sheetHive function-cheat-sheet
Hive function-cheat-sheet
 
Database Query Using SQL_ip.docx
Database Query Using SQL_ip.docxDatabase Query Using SQL_ip.docx
Database Query Using SQL_ip.docx
 
Introduction to Data Science With R Lab Record
Introduction to Data Science With R Lab RecordIntroduction to Data Science With R Lab Record
Introduction to Data Science With R Lab Record
 
Les03 (Using Single Row Functions To Customize Output)
Les03 (Using Single Row Functions To Customize Output)Les03 (Using Single Row Functions To Customize Output)
Les03 (Using Single Row Functions To Customize Output)
 

More from DrkhanchanaR

Unit I-Data Structures_Intoduction.pptx
Unit I-Data Structures_Intoduction.pptxUnit I-Data Structures_Intoduction.pptx
Unit I-Data Structures_Intoduction.pptxDrkhanchanaR
 
Unit 5 internal sorting &amp; files
Unit 5  internal sorting &amp; filesUnit 5  internal sorting &amp; files
Unit 5 internal sorting &amp; filesDrkhanchanaR
 
Unit 4 external sorting
Unit 4   external sortingUnit 4   external sorting
Unit 4 external sortingDrkhanchanaR
 
Unit 3 graph chapter6
Unit 3  graph chapter6Unit 3  graph chapter6
Unit 3 graph chapter6DrkhanchanaR
 
Unit 3 Tree chapter 5
Unit 3  Tree chapter 5Unit 3  Tree chapter 5
Unit 3 Tree chapter 5DrkhanchanaR
 
Unit 2 linked list
Unit 2   linked listUnit 2   linked list
Unit 2 linked listDrkhanchanaR
 
Unit I-Data structures stack & Queue
Unit I-Data structures stack & QueueUnit I-Data structures stack & Queue
Unit I-Data structures stack & QueueDrkhanchanaR
 
Unit I - Evaluation of expression
Unit I - Evaluation of expressionUnit I - Evaluation of expression
Unit I - Evaluation of expressionDrkhanchanaR
 
Unit I- Data structures Introduction, Evaluation of Algorithms, Arrays, Spars...
Unit I- Data structures Introduction, Evaluation of Algorithms, Arrays, Spars...Unit I- Data structures Introduction, Evaluation of Algorithms, Arrays, Spars...
Unit I- Data structures Introduction, Evaluation of Algorithms, Arrays, Spars...DrkhanchanaR
 

More from DrkhanchanaR (9)

Unit I-Data Structures_Intoduction.pptx
Unit I-Data Structures_Intoduction.pptxUnit I-Data Structures_Intoduction.pptx
Unit I-Data Structures_Intoduction.pptx
 
Unit 5 internal sorting &amp; files
Unit 5  internal sorting &amp; filesUnit 5  internal sorting &amp; files
Unit 5 internal sorting &amp; files
 
Unit 4 external sorting
Unit 4   external sortingUnit 4   external sorting
Unit 4 external sorting
 
Unit 3 graph chapter6
Unit 3  graph chapter6Unit 3  graph chapter6
Unit 3 graph chapter6
 
Unit 3 Tree chapter 5
Unit 3  Tree chapter 5Unit 3  Tree chapter 5
Unit 3 Tree chapter 5
 
Unit 2 linked list
Unit 2   linked listUnit 2   linked list
Unit 2 linked list
 
Unit I-Data structures stack & Queue
Unit I-Data structures stack & QueueUnit I-Data structures stack & Queue
Unit I-Data structures stack & Queue
 
Unit I - Evaluation of expression
Unit I - Evaluation of expressionUnit I - Evaluation of expression
Unit I - Evaluation of expression
 
Unit I- Data structures Introduction, Evaluation of Algorithms, Arrays, Spars...
Unit I- Data structures Introduction, Evaluation of Algorithms, Arrays, Spars...Unit I- Data structures Introduction, Evaluation of Algorithms, Arrays, Spars...
Unit I- Data structures Introduction, Evaluation of Algorithms, Arrays, Spars...
 

Recently uploaded

Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 

Recently uploaded (20)

Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 

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.
  • 44. GROUP BY Clause - Examples
  • 46.
  • 47. HAVING Clause – Examples
  • 48.
  • 49. Difference between WHERE and HAVING 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.
  • 55.
  • 56. 1. Equijoin Syntax • SELECT Columnnames FROM tablenames WHERE join condition(s);
  • 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
  • 61. Table Alias - Example
  • 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
  • 73. Self join SQL> SELECT e.Lname ||’,’|| e.Fname Employee 2 s.Lname ||’,’|| s.Fname Manager 3 FROM employee e,employee s 4 WHERE e.supervisor =s.EmployeeId EMPLOYEE MANAGER Houston,Larry Smith,John Roberts,Sandi Smith,John McCall,Alex Dev,Derek Dev,Derek Smith,John Shaw,Jinku Garner,Stanley Garner,Stanley Smith,John Chen,Sunny Roberts,Sandi 7 rows selected SQL>
  • 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
  • 86. INTERSECT The intersection operation works on output from two separate queries and returns rows that appear in both outputs.
  • 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