Introduction to Oracle Functions--(SQL)--Abhishek Sharma


Published on

Published in: Education
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Introduction to Oracle Functions--(SQL)--Abhishek Sharma

  1. 1. Introduction to OracleFunctions and Group By Clause
  2. 2. Introduction to Oracle Functions Functions make the result of the queryeasier and are used to manipulate the datavalues. Functions can accept any number ofconstant values or variables. Thesevariables or constant are called asarguments. SQL functions can performdifferent types of operations such asmodify individual data items, convertcolumn data types, format dates andnumbers etc.
  3. 3. Categories of FunctionsOracle functions are categorized into two categories:• Single Row/Scalar Functions• Group/Aggregate Functions Functions, which operate on single rows and return onevalue per row, are called as Scalar functions or SingleRow Functions.On the other hand functions, which operate on set ofvalues to give one result, are called as Group Functionsor Aggregate Functions.
  4. 4. Single-Row Functions (Scalar functions) These functions act on each row of the table andreturn a single value for each row selected. Thesefunctions may accept one or more arguments and canreturn a value of different data type than that ithas accepted.
  5. 5. Classification of Single Row FunctionsSingle Row Functions can be classified into the followingcategories: (i) Character(ii) Number(iii) Date(iv) Conversion(v) General 
  6. 6. Character Functions•
  7. 7. • length(x)It returns the length of the string x.Example: SQL> Select LENGTH (Ipso Facto) ergo FROM dual;
  8. 8. • ltrim(string[,char(s)])It removes all the blank spaces from the left side of thestring if no char is specified. If we give a char, then itremoves the leading occurrences of that character from thestring.
  9. 9. • Translate(char,find,new) This function is used to find a char and replace it with newcharacter. All occurrences of find are replaced by thecharacter in new. 
  10. 10. •        floor(x) Where x is a number. This function returns the largest integer that is less than or equal to n. FLOOR rounddown to a whole number.
  11. 11. •        round(x[,y]) It rounds off x to the decimal precision of y. If y is negative, rounds to the precision of y places to the left of thedecimal point.
  12. 12. •        sqrt(x) This function returns the square root of the given number x. If the given number x is negative or NULL then the result isNULL. Example: SQL>select sqrt(36) as square_root from dual;
  13. 13. Date Functions
  15. 15. General functions SQL>Select greatest(-2 ,10,’7’) from dual ;SQL>Select least(‘ABCD’,‘abcd’,’xyz’)from dual ;
  16. 16. SQL>Select user from dual; 
  17. 17. Aggregate Functions (Group Functions) These functions are used to produce summarizedresults. They are applied on set of rows to give yousingle value as a result. A group function allows you toperform a data operation on several values in a columnof data as though the column was one collective groupof data. These functions are called group functionsalso, because they are often used in a special clause ofselect statements called a group by clause.
  18. 18. COUNT (x)   This function returns the number of rows or non-null values for column x. When we use * in place of x, it returns the total number of rows in the table.   Syntax: count([distinct|all]column name)  Example:  1. Count the number of employees in the emp table. SQL>Select count(empno) from emp;  The Output is: COUNT(EMPNO) ------------ 16 
  19. 19. List the number of different names in the emp table. SQL>Select count (distinct ename) from emp; The output is:COUNT(DISTINCTENAME)-------------------- 16 List the number of departments in the employee table . SQL>Select count( distinct deptno) from emp; The output is:COUNT(DISTINCTDEPTNO)--------------------- 3
  20. 20. SUM(x)  This function returns the sum of values for thecolumn x. This function is applied on columns having numericdatatype and it returns the numeric value. syntax : sum([distinct|all]column name) Example:List the total salary paid to the employees in the emp table.  SQL>select sum(sal) from emp ; The output is: SUM(SAL) --------- 29025
  21. 21. AVG(x)  This function returns the average of values forthe column x. This function is applied on columns havingnumeric datatype and it returns the numeric value. It ignoresthe null values in the column x.  syntax : avg([distinct|all]column name) Example: List the average salary and the number of employees in theemp table .  SQL>select avg(sal) ,count(sal) from emp ;
  22. 22. MIN(x) This function returns the minimum of values for the column x for all the rows .this function can be applied on any datatype . syntax : min([distinct|all]column name)   Example: List the minimum salary in the emp table .SQL>select min(sal) from emp ;The output is:MIN(SAL)-------- 800
  23. 23. MAX(x) This function returns the maximum of values for the column x for all the rows .this function can be applied on any datatype. syntax : max([distinct|all]column name)   Example: List the maximum salary and commission in the emp table .SQL>select max(sal) ,max(comm) from emp ;
  24. 24. Note : The avg() and sum() functions will always be appliedon numeric datatype while min() and max() functions can beapplied on any datatype. Example SQL>select avg(sal),sum(sal),min(ename),max(ename) fromemp ;
  25. 25. Exercise : •list the names of the employees earning minimum salary .•list the names of the employees earning second highestsalary .•list the details of the employees who earn salary greaterthan the average salary . also count their number .•count the number of employees whose salary is equal tothe highest salary .•list the number of employees ,their average salary,minimum salary and maximum salary in the employeetable. 
  26. 26. Grouping Data with GROUP BYGROUP BY clause is used to group or categorize the data. In otherwords it divide rows in a table into smaller groups. We can thenuse the group functions to return summary information for eachgroup. If no GROUP BY clause is specified, then the default grouping isthe entire result set. When the query executes and the data isfetched, it is grouped based on the GROUP BY clause and thegroup function is applied.
  27. 27. Syntax:SELECT column,group_function(column) FROM table[WHERE condition][GROUP BY group_by_expression][ORDER BY column];Here, group_by_expression specifies columns whose valuesdetermine the basis for grouping rows.
  28. 28. For example, If we have to find the total salary of each departmentmanually, first we group the records on the basis of departmentnumber and then we apply the sum function on salary of each groupto obtain the required result. Similarly in SQL we apply the GROUPBY clause on deptno and then calculate the total salary for each groupby Sum(sal) function as shown below: SQL>SELECT deptno, Sum(sal) FROM emp GROUP BY deptno; The output is: DEPTNO SUM(SAL) 10 2916.6667 20 2175 30 1566.6667
  29. 29. Here is how this SELECT statement, containing a GROUP BYclause, is evaluated:• The SELECT clause specifies the columns to be retrieved i.eDepartment number column in the EMP table, the sum of all thesalaries in the group you specified in the GROUP By clause• The FROM clause specifies the tables that the database mustaccess i.e EMP table.• The WHERE clause specifies the rows to be retrieved. Sincethere is no WHRE clause, by default all rows are retrieved.
  30. 30. The GROUP BY clause specifies how the rows should be grouped. Department number groups the rows, so the AVG function that is being applied to the salary column will calculate the average salary for each department. • List the average salary of each job in the emp table.SQL>SELECT JOB,AVG(SAL) FROM EMP GROUP BY JOB;•List the maximum salary for each dept.SQL>SELECT DEPTNO,MAX(SAL) FROM EMP GROUP BYDEPTNO;
  31. 31. Grouping by more than one columnSometimes there is a need to see results for groups within groups.For example if we have to find the total salary being paid to eachjob title, within each department. Then there is a need to havinggrouping on department number and within each departmentnumber grouping on the basis of job or in other words there is aneed for grouping within a group.Thus, the EMP table is grouped first by department number, andwithin that grouping, it is grouped by job title. For example, the twoclerks in department 20 are grouped together and a single result(total salary) is produced for all clerks people within that group.
  32. 32. SQL> SELECT deptno,job,sum(sal) FROM emp GROUP BYdeptno, job;The output is:
  33. 33. By above example it is clear that we can return summary results forgroups and subgroups by listing more than one GROUP BY column.We can determine the default sort order of the results by the order ofthe columns in the GROUP BY clause.The SELECT clause specifies the column to be retrieved:• Department number in the EMP table• Job title in the EMP table• The sum of all the salaries in the group that you specified inthe GROUP BY clause• The FROM clause specifies the tables that the database mustaccess the EMP table• The GROUP BY clause specifies how we must group the rowsFirst, department number groups the rows. Second, within thedepartment number groups, the rows are grouped by job title. So, theSUM function is being applied to the salary column for all job titleswithin each department number group.
  34. 34. Illegal Queries Using Group FunctionsWhenever you use a mixture of individual items (DEPTNO) andgroup functions (COUNT) in the same select statement, you mustinclude a Group By clause that specifies the individual items (inthis case, DEPTNO). If the GROUP By clause is missing, then theerror message “not a single-group group function” appears and anasterisk (*) points to the offending column. You can correct theerror by adding the GROUP BY clause.
  35. 35. For example, following is the illegal query: SQL> SELECT deptno, COUNT(ename) FROM emp; The Output will be: Column missing in the Group By clause Select deptno,count(ename) * ERROR at line 1: ORA-00937: not a single-group group function In above select statement individual items DEPTNO and group function COUNT appears in the same SELECT statement without GROUP BY clause which results error, it can be corrected by adding the GROUP BY clause as shown below:SQL> SELECT deptno,COUNT(ename) FROM emp Group By deptno;
  36. 36. DEPTNO COUNT(ENAME) 10 3 20 5 30 6Note:Any column or expression in the SELECT list that is not anaggregate function must be in the GROUP By clause.
  37. 37. Restricting Group ResultsAs we use the WHERE clause to restrict the rows that we select,we can use the HAVING clause to restrict groups.For example: To find the maximum salary of each department,but show only the departments that have a maximum salary ofmore than Rs.2900, we need to do the following.• Find the maximum salary for each department by groupingby department number.• Restrict the groups to those departments with a maximumsalary greater the Rs.2900.
  38. 38. Syntax:SELECT column, group_functionFROM table{WHERE condition][GROUP BY group_by_expression][HAVING group_condition][ORDER BY Column];
  39. 39. Here we use the HAVING clause to specify which groups are to bedisplayed. Therefore, we further restrict the groups on the basis ofaggregate information.In the syntax: HAVING clause restricts the groups of rows returned to thosegroups for which the specified condition is TRUEThe Oracle Server performs the following steps when you use theHAVING clause:
  40. 40. • Rows are grouped• The group function is applied to the group.• The groups that match the criteria in the HAVING clause aredisplayed.The HAVING clause can precede the GROUP By clause, but it isrecommended that you place the GROUP By clause first because it ismore logical. Groups are formed and group functions are calculatedbefore the HAVING clause is applied to the groups in the SELECTlist.
  41. 41. For example: To find the maximum salary of each department, butshow only the departments that have a maximum salary of more thanRs.2900SQL> SELECT deptno,max(sal) FROM emp GROUP BY deptno Having max(sal)>2900;The output is:DEPTNO MAX(SAL)10 500020 3000
  42. 42. Use of WHERE clause with GROUP BY clauseList the total salary, maximum and minimum salary and theaverage salary of employees job wise, for department number 20and display only those rows having average salary greater than1000SQL>SELECT job, SUM(sal), avg(sal), max(sal), min(sal) fromempWHERE deptno=20GROUP by jobHAVING AVG(sal)>1000;
  43. 43. The output is: JOB SUM(SAL) AVG(SAL) MAX(SAL) MIN(SAL) ANALYST 6000 3000 3000 3000 MANAGER 2975 2975 2975 2975
  44. 44. SQL> SELECT job, SUM(sal) PAYROLLFROM empWHERE job NOT LIKE SALE%GROUP BY jobHAVING SUM(sal)>5000ORDER BY SUM(sal);The output is:JOB PAYROLLANALYST 6000MANAGER 8275 The above query displays the job title and total monthly salary foreach job title with a total payroll exceeding Rs.5000. The exampleexcludes salespeople and sorts the list by the total monthly salary.
  45. 45. Display total no of suppliers supplying red partDisplay total qty supplied by by each supplierDisplay total Qty supplied for each part excluding P3Only display those where supplied qty is greater than100Display info in descending order of Qty Select Pno, Sum(QTY) from SP WHERE PNO<>’P3’ GROUP BY PNO HAVING SUM(QTY)>1000 ORDER BY PNO;
  46. 46. Display total Qty supplied for each part excluding part having redcolor, Only display those where supplied qty is greater than100Select Pno, Sum(QTY) from SP WHERE PNO NOT IN(SELECTPNO FROM P WHERE COLOR=‘RED’) GROUP BY PNOHAVING SUM(QTY)>1000 ORDER BY PNO;