Upload
giles-jennings
View
238
Download
2
Embed Size (px)
Citation preview
Single-Row Functions
SQL Functions
Functions are a very powerful feature of SQL and can be used to do the following:
•Perform calculations on data
•Modify individual data items
•Manipulate output for groups of rows
•Format dates and numbers for display
•Convert column datatypes
SQL functions may accept arguments and always return a value.
Note: Most of the functions described in this lesson are specific to Oracle’s version of SQL.
Two Types of SQL FunctionsTwo Types of SQL Functions
FunctionsFunctions
Single-row Single-row functionsfunctions
Multiple-rowMultiple-rowfunctionsfunctions
There are two distinct types of functions:
•Single-row functions
•Multiple-row functions
Single-Row Functions
These functions operate on single rows only and return one result per row. There are different types of single-row functions. This lesson covers the following ones:
•Character - Number - Date - Conversion
Single-row functions are used to manipulate data items. They accept one or more arguments and return one value for each row returned by the query. An argument can be one of the following:
•User-supplied constant
•Variable value
•Column name
•Expression
Features of single-row functions:
•Act on each row returned in the query
•Return one result per row
•May return a data value of a different type than that referenced
•May expect one or more arguments
•Can be used in SELECT, WHERE, and ORDER BY clauses; can be nested
function_name (column|expression, [arg1, arg2,...])function_name (column|expression, [arg1, arg2,...])
Single-Row FunctionsSingle-Row Functions
ConversionConversion
CharacterCharacter
NumberNumber
DateDate
GeneralGeneralSingle-row Single-row functionsfunctions
•Character functionsccept character input and can return both character and number values
•Number functionsAccept numeric input and return numeric values
•Date functionsOperate on values of the date datatype (All date functions return a value of date datatype except the MONTHS_BETWEEN function, which returns a number.)
•Conversion functionsConvert a value from one datatype to another
•General functions:
–NVL function
–DECODE function
Character FunctionsCharacter FunctionsCharacterCharacterfunctionsfunctions
LOWERLOWER
UPPERUPPER
INITCAPINITCAP
CONCATCONCAT
SUBSTRSUBSTR
LENGTHLENGTH
INSTRINSTR
LPADLPAD
Case conversion Case conversion functionsfunctions
Character manipulationCharacter manipulationfunctionsfunctions
Using Case Conversion FunctionsUsing Case Conversion Functions
Display the employee number, name, and department number for employee Blake.Display the employee number, name, and department number for employee Blake.
SQL> SELECT empno, ename, deptno 2 FROM emp 3 WHERE ename = 'blake';no rows selectedno rows selected
SQL> SELECT empno, ename, deptno 2 FROM emp 3 WHERE ename = 'blake';no rows selectedno rows selected
EMPNO ENAME DEPTNO--------- ---------- --------- 7698 BLAKE 30
EMPNO ENAME DEPTNO--------- ---------- --------- 7698 BLAKE 30
SQL> SELECT empno, ename, deptno 2 FROM emp 3 WHERE LOWER(ename) = 'blake';
Example:
Display the values in the columns; ename, job, at the same field with a space btween them displying them in lowercase, under a new column name as Employee Details. More over the values in the column job should be initial capitalized and displayed under the column name Employee Job the values in the column ename should be in uppercase and displayed under the column name as Employee name for all the employees whose name starts with letter A.
CONCAT('Good', 'String')
SUBSTR('String',1,3)
LENGTH('String')
INSTR('String', 'r')
LPAD(sal,10,'*')
TRIM( ‘S’ FROM ‘SSMITH’)
GoodString
Str
6
3
******5000
MITH
Function Result
Character Manipulation FunctionsCharacter Manipulation Functions
Manipulate character stringsManipulate character strings
Character Manipulation Functions
•CONCATJoins values together (You are limited to using two parameters with CONCAT.)
•SUBSTRExtracts a string of determined length
•LENGTHShows the length of a string as a numeric value
•INSTRFinds numeric position of a named character
•LPADPads the character value right-justified
•Trim: Trims heading or trailing characters (or both) from a character string if trim_character or trim_source is a character literal. You must enclose it in single quotes.
Using the Character Manipulation Functions
Using the Character Manipulation Functions
SQL> SELECT ename, CONCAT (ename, job), LENGTH(ename), 2 INSTR(ename, 'A') 3 FROM emp 4 WHERE SUBSTR(job,1,5) = 'SALES';
ENAME CONCAT(ENAME,JOB) LENGTH(ENAME) INSTR(ENAME,'A')---------- ------------------- ------------- ----------------MARTIN MARTINSALESMAN 6 2ALLEN ALLENSALESMAN 5 1TURNER TURNERSALESMAN 6 0WARD WARDSALESMAN 4 2
SQL> SELECT ename, CONCAT(ename, job), LENGTH(ename),INSTR(ename, 'A')
2 FROM emp 3 WHERE SUBSTR(ename, -1, 1) = 'N';
ENAME CONCAT(ENAME,JOB) LENGTH(ENAME) INSTR(ENAME,'A')-------- ------------------- ------------- ----------------MARTIN MARTINSALESMAN 6 2ALLEN ALLENSALESMAN 5 1
Example
Modify the SQL statement on the slide to display the data for those employees whose names end with an N.
Number FunctionsNumber Functions
ROUND: Rounds value to specified decimal
ROUND(45.926, 2) 45.93TRUNC: Truncates value to specified
decimalTRUNC(45.926, 2) 45.92
MOD: Returns remainder of divisionMOD(1600, 300) 100
ROUND: Rounds value to specified decimal
ROUND(45.926, 2) 45.93TRUNC: Truncates value to specified
decimalTRUNC(45.926, 2) 45.92
MOD: Returns remainder of divisionMOD(1600, 300) 100
Using the ROUND FunctionUsing the ROUND Function
SQL> SELECT ROUND(45.923,2), ROUND(45.923,0), 2 ROUND(45.923,-1) 3 FROM DUAL;
ROUND(45.923,2) ROUND(45.923,0) ROUND(45.923,-1)--------------- -------------- ----------------- 45.92 46 50
SQL> SELECT TRUNC(45.923,2), TRUNC(45.923), 2 TRUNC(45.923,-1) 3 FROM DUAL;
TRUNC(45.923,2) TRUNC(45.923) TRUNC(45.923,-1)--------------- ------------- --------------- 45.92 45 40
Using the TRUNC FunctionUsing the TRUNC Function
Using the MOD FunctionUsing the MOD Function
Calculate the remainder of the ratio of salary to commission for all employees whose job title is salesman.
Calculate the remainder of the ratio of salary to commission for all employees whose job title is salesman.SQL> SELECT ename, sal, comm, MOD(sal, comm)
2 FROM emp 3 WHERE job = 'SALESMAN';
ENAME SAL COMM MOD(SAL,COMM)---------- --------- --------- -------------MARTIN 1250 1400 1250ALLEN 1600 300 100TURNER 1500 0 1500WARD 1250 500 250
Working with DatesWorking with DatesOracle stores dates in an internal
numeric format: century, year, month, day, hours, minutes, seconds.
The default date format is DD-MON-YY.SYSDATE is a function returning date
and time.DUAL is a dummy table used to view
SYSDATE.
Oracle stores dates in an internal numeric format: century, year, month, day, hours, minutes, seconds.
The default date format is DD-MON-YY.SYSDATE is a function returning date
and time.DUAL is a dummy table used to view
SYSDATE.
Arithmetic with DatesArithmetic with Dates
Add or subtract a number to or from a date for a resultant date value.
Subtract two dates to find the number of days between those dates.
Add hours to a date by dividing the number of hours by 24.
Add or subtract a number to or from a date for a resultant date value.
Subtract two dates to find the number of days between those dates.
Add hours to a date by dividing the number of hours by 24.
Operation Result Descriptiondate + number Date Adds a number of days to a datedate - number Date Subtracts a number of days from a datedate - date Number of daysSubtracts one date from anotherdate + number/24 Date Adds a number of hours to a date
You can perform the following operations:
Using Arithmetic Operatorswith Dates
Using Arithmetic Operatorswith Dates
SQL> SELECT ename, (SYSDATE-hiredate)/7 WEEKS 2 FROM emp 3 WHERE deptno = 10;
ENAME WEEKS---------- ---------KING 830.93709CLARK 853.93709MILLER 821.36566
Date FunctionsDate Functions
Number of monthsbetween two dates
MONTHS_BETWEEN
ADD_MONTHS
NEXT_DAY
LAST_DAY
ROUND
TRUNC
Add calendar months to date
Next day of the date specified
Last day of the month
Round date
Truncate date
Function Description
• MONTHS_BETWEEN ('01-SEP-95','11-JAN-94')MONTHS_BETWEEN ('01-SEP-95','11-JAN-94')
Using Date FunctionsUsing Date Functions
• ADD_MONTHS ('11-JAN-94',6)ADD_MONTHS ('11-JAN-94',6)
• NEXT_DAY ('01-SEP-95','FRIDAY') NEXT_DAY ('01-SEP-95','FRIDAY')
• LAST_DAY('01-SEP-95')LAST_DAY('01-SEP-95')
19.677419419.6774194
'11-JUL-94''11-JUL-94'
'08-SEP-95''08-SEP-95'
'30-SEP-95''30-SEP-95'
e.g. (using date functions )
Date Functions (continued)
For all employees employed for fewer than 200 months, display the employee number, hire date, number of months employed, six-month review date, and last day of the month when hired.
SQL> SELECT empno, hiredate, 2 MONTHS_BETWEEN(SYSDATE, hiredate) TENURE, 3 ADD_MONTHS(hiredate, 6) REVIEW, 4 LAST_DAY(hiredate) 5 FROM emp 6 WHERE MONTHS_BETWEEN (SYSDATE,
hiredate)<200;
Using Date FunctionsUsing Date Functions
• ROUND('25-JUL-95','MONTH') 01-AUG-95ROUND('25-JUL-95','MONTH') 01-AUG-95
• ROUND('25-JUL-95','YEAR') ROUND('25-JUL-95','YEAR') 01-JAN-96 01-JAN-96
• TRUNC('25-JUL-95','MONTH') TRUNC('25-JUL-95','MONTH') 01-JUL-95 01-JUL-95
• TRUNC('25-JUL-95','YEAR')TRUNC('25-JUL-95','YEAR') 01-JAN- 01-JAN-9595
ExampleCompare the hire dates for all employees who started in 1982. Display the employee number, hire date, and month started using the ROUND and TRUNC functions.
SQL> SELECT empno, hiredate,
2 ROUND(hiredate, 'MONTH'), TRUNC(hiredate, 'MONTH')
3 FROM emp
4 WHERE hiredate like '%82';