Copyright © 2006, Oracle. All rights reserved.
Using Single-Row Functions to
Customize Output
Copyright © 2006, Oracle. All rights reserved. 3 - 2
Objectives
After completing this lesson, you should be able to do
the following:
•
Describe various types of functions that are
available in SQL
•
Use character, number, and date functions in
SELECT
statements
•
Describe the use of conversion functions
Objectives
Functions make the basic query block more powerful, and they are used to manipulate data values. This is the first of two lessons that explore functions. It focuses on single-row character, number, and date functions, as well as those functions that convert data from one type to another (for example, conversion from character data to numeric data).
Copyright © 2006, Oracle. All rights reserved. 3 - 3
SQL Functions
Function Input arg 1 arg 2 arg n Function performs action Output Result value SQL FunctionsFunctions are a very powerful feature of SQL. They 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 data types
SQL functions sometimes take arguments and always return a value.
Note:Most of the functions that are described in this lesson are specific to the Oracle version of SQL.
Copyright © 2006, Oracle. All rights reserved. 3 - 4
Two Types of SQL Functions
Single-row functions
Multiple-row functions Return one result
per row
Return one result per set of rows Functions
SQL Functions (continued) There are two 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 • General Multiple-Row Functions
Copyright © 2006, Oracle. All rights reserved. 3 - 5
Single-Row Functions
Single-row functions:
•
Manipulate data items
•
Accept arguments and return one value
•
Act on each row that is returned
•
Return one result per row
•
May modify the data type
•
Can be nested
•
Accept arguments that can be a column or an
expression
function_name [(arg1, arg2,...)]
Single-Row Functions
Single-row functions are used to manipulate data items. They accept one or more arguments and return one value for each row that is 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 include:
• Acting on each row that is returned in the query • Returning one result per row
Copyright © 2006, Oracle. All rights reserved. 3 - 6
Single-Row Functions
Conversion Character Number Date General Single-row functionsSingle-Row Functions (continued)
This lesson covers the following single-row functions:
• Character functions:Αccept character input and can return both character and number values
• Number functions:Accept numeric input and return numeric values
• Date functions:Operate on values of the DATEdata type (All date functions return a value of DATEdata type except the MONTHS_BETWEENfunction, which returns a number.) • Conversion functions:Convert a value from one data type to another
• General functions: - NVL - NVL2 - NULLIF - COALESCE - CASE
Function Purpose
LOWER(column|expression) Converts alpha character values to lowercase
UPPER(column|expression) Converts alpha character values to uppercase
INITCAP(column|expression) Converts alpha character values to uppercase for the first letter of each word; all other letters in lowercase
Copyright © 2006, Oracle. All rights reserved. 3 - 7
Character Functions
Character functions LOWER UPPER INITCAP CONCAT SUBSTR LENGTH INSTR LPAD | RPAD TRIM REPLACE Case-manipulation functions Character-manipulation functions Character FunctionsSingle-row character functions accept character data as input and can return both character and numeric values. Character functions can be divided into the following:
• Case-manipulation functions • Character-manipulation functions
Function Purpose
LENGTH(column|expression) Returns the number of characters in the expression
INSTR(column|expression, ’string’, [,m], [n] )
Returns the numeric position of a named string. Optionally, you can provide a position m to start searching, and the occurrence n of the string. m and n default to 1, meaning start the search at the beginning of the search and report the first occurrence.
LPAD(column|expression, n,
'string')
RPAD(column|expression, n,
'string')
Pads the character value right-justified to a total width of n
character positions
Pads the character value left-justified to a total width of n
character positions
TRIM(leading|trailing|both, trim_character FROM
trim_source)
Enables you to trim 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 quotation marks.
This is a feature that is available in Oracle8i and later versions.
REPLACE(text, search_string, replacement_string)
Searches a text expression for a character string and, if found, replaces it with a specified replacement string
Copyright © 2006, Oracle. All rights reserved. 3 - 9
Case-Manipulation Functions
These functions convert case for character strings:
sql course LOWER('SQL Course') Sql Course INITCAP('SQL Course') SQL COURSE UPPER('SQL Course') Result Function Case-Manipulation Functions
LOWER, UPPER, and INITCAPare the three case-conversion functions. • LOWER:Converts mixed-case or uppercase character strings to lowercase • UPPER:Converts mixed-case or lowercase character strings to uppercase
• INITCAP:Converts the first letter of each word to uppercase and remaining letters to lowercase
SELECT 'The job id for '||UPPER(last_name)||' is ' ||LOWER(job_id) AS "EMPLOYEE DETAILS"
Copyright © 2006, Oracle. All rights reserved. 3 - 10
SELECT employee_id, last_name, department_id FROM employees
WHERE LOWER(last_name) = 'higgins';
Using Case-Manipulation Functions
Display the employee number, name, and department
number for employee Higgins:
SELECT employee_id, last_name, department_id FROM employees
WHERE last_name = 'higgins';
no rows selected
Using Case-Manipulation Functions
The slide example displays the employee number, name, and department number of employee Higgins.
The WHEREclause of the first SQL statement specifies the employee name as higgins. Because all the data in the EMPLOYEEStable is stored in proper case, the name higginsdoes not find a match in the table, and no rows are selected.
The WHEREclause of the second SQL statement specifies that the employee name in the
EMPLOYEEStable is compared to higgins, converting the LAST_NAMEcolumn to lowercase for comparison purposes. Because both names are now lowercase, a match is found and one row is selected. The WHEREclause can be rewritten in the following manner to produce the same result:
...WHERE last_name = 'Higgins'
Copyright © 2006, Oracle. All rights reserved. 3 - 11
Character-Manipulation Functions
These functions manipulate character strings:
BLACK and BLUE REPLACE
('JACK and JUE','J','BL')
10 LENGTH('HelloWorld') 6 INSTR('HelloWorld', 'W') *****24000 LPAD(salary,10,'*') 24000***** RPAD(salary, 10, '*') HelloWorld CONCAT('Hello', 'World') elloWorld TRIM('H' FROM 'HelloWorld')
Hello SUBSTR('HelloWorld',1,5)
Result Function
Character-Manipulation Functions
CONCAT, SUBSTR, LENGTH, INSTR, LPAD, RPAD, and TRIMare the character-manipulation functions that are covered in this lesson.
• CONCAT:Joins values together (You are limited to using two parameters with CONCAT.) • SUBSTR:Extracts a string of determined length
• LENGTH:Shows the length of a string as a numeric value • INSTR:Finds the numeric position of a named character • LPAD:Pads the character value right-justified
• RPAD:Pads the character value left-justified
• TRIM:Trims heading or trailing characters (or both) from a character string (If
Copyright © 2006, Oracle. All rights reserved. 3 - 12
SELECT employee_id, CONCAT(first_name, last_name) NAME, job_id, LENGTH (last_name),
INSTR(last_name, 'a') "Contains 'a'?" FROM employees
WHERE SUBSTR(job_id, 4) = 'REP';
Using the Character-Manipulation Functions
2
3
1
2
1
3
Using the Character-Manipulation Functions
The slide example displays employee first names and last names joined together, the length of the employee last name, and the numeric position of the letter ain the employee last name for all employees who have the string REPcontained in the job ID starting at the fourth position of the job ID.
Example
Modify the SQL statement in the slide to display the data for those employees whose last names end with the letter n.
SELECT employee_id, CONCAT(first_name, last_name) NAME, LENGTH (last_name), INSTR(last_name, 'a') "Contains 'a'?" FROM employees
Copyright © 2006, Oracle. All rights reserved. 3 - 13
Number Functions
•
ROUND
: Rounds value to specified decimal
•
TRUNC
: Truncates value to specified decimal
•
MOD
: Returns remainder of division
100
MOD(1600, 300)
45.93
ROUND(45.926, 2)
45.92
TRUNC(45.926, 2)
Result Function Number FunctionsNumber functions accept numeric input and return numeric values. This section describes some of the number functions.
Function Purpose
ROUND(column|expression, n) Rounds the column, expression, or value to n decimal places or, if n is omitted, no decimal places (If n is
negative, numbers to left of the decimal point are rounded.) TRUNC(column|expression, n) Truncates the column, expression, or value to n decimal
places or, if n is omitted, n defaults to zero MOD(m,n) Returns the remainder of m divided by n
Copyright © 2006, Oracle. All rights reserved. 3 - 14
SELECT ROUND(45.923,2), ROUND(45.923,0), ROUND(45.923,-1)
FROM DUAL;
Using the
ROUND
Function
DUAL
is a dummy table that you can use to view results
from functions and calculations.
3
3
1
2
1
2
ROUNDFunction
The ROUNDfunction rounds the column, expression, or value to ndecimal places. If the second argument is 0 or is missing, the value is rounded to zero decimal places. If the second argument is 2, the value is rounded to two decimal places. Conversely, if the second argument is –2, the value is rounded to two decimal places to the left (rounded to the nearest unit of 10).
The ROUNDfunction can also be used with date functions. You will see examples later in this lesson.
DUALTable
The DUALtable is owned by the user SYSand can be accessed by all users. It contains one column, DUMMY, and one row with the value X. The DUALtable is useful when you want to return a value once only (for example, the value of a constant, pseudocolumn, or expression that is not derived from a table with user data). The DUALtable is generally used for SELECTclause syntax completeness, because both SELECTand FROMclauses are mandatory, and several
Copyright © 2006, Oracle. All rights reserved. 3 - 15
Using the
TRUNC
Function
SELECT TRUNC(45.923,2), TRUNC(45.923), TRUNC(45.923,-1) FROM DUAL;
3
3
1
2
1
2
TRUNCFunctionThe TRUNCfunction truncates the column, expression, or value to n decimal places. The TRUNCfunction works with arguments similar to those of the ROUNDfunction. If the second argument is 0 or is missing, the value is truncated to zero decimal places. If the second argument is 2, the value is truncated to two decimal places. Conversely, if the second argument is –2, the value is truncated to two decimal places to the left. If the second argument is –1, the value is truncated to one decimal place to the left.
Copyright © 2006, Oracle. All rights reserved. 3 - 16
SELECT last_name, salary, MOD(salary, 5000) FROM employees
WHERE job_id = 'SA_REP';
Using the
MOD
Function
For all employees with job title of Sales Representative,
calculate the remainder of the salary after it is divided by
5,000.
MODFunction
The MODfunction finds the remainder of the first argument divided by the second argument. The slide example calculates the remainder of the salary after dividing it by 5,000 for all employees whose job ID is SA_REP.
Copyright © 2006, Oracle. All rights reserved. 3 - 17
SELECT last_name, hire_date FROM employees
WHERE hire_date < '01-FEB-88' ';';
Working with Dates
•
The Oracle database stores dates in an internal numeric
format: century, year, month, day, hours, minutes, and
seconds.
•
The default date display format is DD-MON-RR.
–
Enables you to store 21st-century dates in the
20th century by specifying only the last two digits of
the year
–
Enables you to store 20th-century dates in the
21st century in the same way
Oracle Date Format
The Oracle database stores dates in an internal numeric format, representing the century, year, month, day, hours, minutes, and seconds.
The default display and input format for any date is DD-MON-RR. Valid Oracle dates are between January 1, 4712 B.C., and December 31, 9999 A.D.
In the example in the slide, the HIRE_DATEcolumn output is displayed in the default format DD-MON-RR. However, dates are not stored in the database in this format. All the components of the date and time are stored. So, although a HIRE_DATEsuch as 17-JUN-87 is displayed as day, month, and year, there is also timeand centuryinformation associated with the date. The complete data might be June 17, 1987, 5:10:43 p.m.
Oracle Date Format (continued) This data is stored internally as follows:
CENTURY YEAR MONTH DAY HOUR MINUTE SECOND
19 87 06 17 17 10 43
Centuries and the Year 2000
When a record with a date column is inserted into a table, the centuryinformation is picked up from the SYSDATEfunction. However, when the date column is displayed on the screen, the century component is not displayed (by default).
The DATEdata type always stores year information as a four-digit number internally: two digits for the century and two digits for the year. For example, the Oracle database stores the year as 1987 or 2004, and not just as 87 or 04.
Copyright © 2006, Oracle. All rights reserved. 3 - 19
Working with Dates
SYSDATE
is a function that returns:
•
Date
•
Time
SYSDATEFunction
SYSDATEis a date function that returns the current database server date and time. You can use SYSDATEjust as you would use any other column name. For example, you can display the current date by selecting SYSDATEfrom a table. It is customary to select SYSDATEfrom a dummy table called DUAL.
Example
Display the current date using the DUALtable. SELECT SYSDATE
Copyright © 2006, Oracle. All rights reserved. 3 - 20
Arithmetic 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.
Arithmetic with Dates
Because the database stores dates as numbers, you can perform calculations using arithmetic operators such as addition and subtraction. You can add and subtract number constants as well as dates.
You can perform the following operations:
Operation Result Description
date + number Date Adds a number of days to a date date – number Date Subtracts a number of days from a date date – date Number of days Subtracts one date from another date + number/24 Date Adds a number of hours to a date
Copyright © 2006, Oracle. All rights reserved. 3 - 21
SELECT last_name, (SYSDATE-hire_date)/7 AS WEEKS FROM employees
WHERE department_id = 90;
Using Arithmetic Operators
with Dates
Arithmetic with Dates (continued)
The example in the slide displays the last name and the number of weeks employed for all employees in department 90. It subtracts the date on which the employee was hired from the current date (SYSDATE) and divides the result by 7 to calculate the number of weeks that a worker has been employed.
Note:SYSDATEis a SQL function that returns the current date and time. Your results may differ from the example.
Copyright © 2006, Oracle. All rights reserved. 3 - 22
Date Functions
Next day of the date specified NEXT_DAY
Last day of the month LAST_DAY
Round date ROUND
Truncate date TRUNC
Number of months between two dates MONTHS_BETWEEN
Add calendar months to date ADD_MONTHS
Result Function
Date Functions
Date functions operate on Oracle dates. All date functions return a value of DATEdata type except MONTHS_BETWEEN, which returns a numeric value.
• MONTHS_BETWEEN(date1, date2):Finds the number of months between date1 and date2. The result can be positive or negative. If date1is later than date2, the result is positive; if date1is earlier than date2, the result is negative. The noninteger part of the result represents a portion of the month.
• ADD_MONTHS(date, n):Adds nnumber of calendar months todate. The value ofn must be an integer and can be negative.
• NEXT_DAY(date, 'char'):Finds the date of the next specified day of the week ('char')following date. The value of charmay be a number representing a day or a character string.
• LAST_DAY(date):Finds the date of the last day of the month that contains date • ROUND(date[,'fmt']):Returns daterounded to the unit that is specified by the
Copyright © 2006, Oracle. All rights reserved. 3 - 23
Using Date Functions
'08-SEP-95' NEXT_DAY ('01-SEP-95','FRIDAY') '28-FEB-95' LAST_DAY ('01-FEB-95') 19.6774194 MONTHS_BETWEEN ('01-SEP-95','11-JAN-94') '11-JUL-94' ADD_MONTHS ('11-JAN-94',6) Result Function
Date Functions (continued)
For example, display the employee number, hire date, number of months employed, six-month review date, first Friday after hire date, and last day of the hire month for all employees who have been employed for fewer than 80 months.
SELECT employee_id, hire_date,
MONTHS_BETWEEN (SYSDATE, hire_date) TENURE, ADD_MONTHS (hire_date, 6) REVIEW,
NEXT_DAY (hire_date, 'FRIDAY'), LAST_DAY(hire_date) FROM employees
Copyright © 2006, Oracle. All rights reserved. 3 - 24
Using Date Functions
Assume
SYSDATE = '25-JUL-03'
:
01-JUL-03 TRUNC(SYSDATE ,'MONTH') 01-JAN-03 TRUNC(SYSDATE ,'YEAR') 01-AUG-03 ROUND(SYSDATE,'MONTH') 01-JAN-04 ROUND(SYSDATE ,'YEAR') Result Function
Date Functions (continued)
The ROUNDand TRUNCfunctions can be used for number and date values. When used with dates, these functions round or truncate to the specified format model. Therefore, you can round dates to the nearest year or month.
Example
Compare the hire dates for all employees who started in 1997. Display the employee number, hire date, and start month using the ROUNDand TRUNCfunctions.
SELECT employee_id, hire_date,
ROUND(hire_date, 'MONTH'), TRUNC(hire_date, 'MONTH') FROM employees
Copyright © 2006, Oracle. All rights reserved. 3 - 25
Practice 3: Overview of Part 1
This practice covers the following topics:
•
Writing a query that displays the current date
•
Creating queries that require the use of numeric,
character, and date functions
•
Performing calculations of years and months of
service for an employee
Practice 3: Overview of Part 1
Part 1 of this lesson’s practice provides a variety of exercises using different functions that are available for character, number, and date data types.
Copyright © 2006, Oracle. All rights reserved. 3 - 26
Conversion Functions
Implicit data type conversion
Explicit data type conversion Data type
conversion
Conversion Functions
In addition to Oracle data types, columns of tables in an Oracle database can be defined using ANSI, DB2, and SQL/DS data types. However, the Oracle server internally converts such data types to Oracle data types.
In some cases, the Oracle server uses data of one data type where it expects data of a different data type. When this happens, the Oracle server can automatically convert the data to the expected data type. This data type conversion can be done implicitlyby the Oracle server or explicitlyby the user.
Implicit data type conversions work according to the rules that are explained in the next two slides.
Explicit data type conversions are done by using the conversion functions. Conversion functions convert a value from one data type to another. Generally, the form of the function names follows the convention data type TO data type. The first data type is the input data type; the
Copyright © 2006, Oracle. All rights reserved. 3 - 27
Implicit Data Type Conversion
For assignments, the Oracle server can automatically
convert the following:
VARCHAR2 NUMBER VARCHAR2 DATE NUMBER VARCHAR2 or CHAR DATE VARCHAR2 or CHAR To From
Implicit Data Type Conversion
The assignment succeeds if the Oracle server can convert the data type of the value used in the assignment to that of the assignment target.
For example, the expression hire_date > '01-JAN-90'results in the implicit conversion from the string '01-JAN-90'to a date.
Copyright © 2006, Oracle. All rights reserved. 3 - 28
Implicit Data Type Conversion
For expression evaluation, the Oracle Server can
automatically convert the following:
NUMBER VARCHAR2 or CHAR DATE VARCHAR2 or CHAR To From
Implicit Data Type Conversion (continued)
In general, the Oracle server uses the rule for expressions when a data type conversion is needed in places that are not covered by a rule for assignment conversions.
For example, the expression salary = '20000'results in the implicit conversion of the string '20000'to the number 20000.
Note:CHARto NUMBERconversions succeed only if the character string represents a valid number.
Copyright © 2006, Oracle. All rights reserved. 3 - 29
Explicit Data Type Conversion
NUMBER
CHARACTER
TO_CHAR
TO_NUMBER
DATE
TO_CHAR
TO_DATE
Explicit Data Type Conversion
SQL provides three functions to convert a value from one data type to another:
Function Purpose
TO_CHAR(number|date,[ fmt],
[nlsparams]) Converts a number or date value to a VARCHAR2 character string with format model fmt
Number conversion: The nlsparams parameter specifies the following characters, which are returned by number format elements: • Decimal character
Copyright © 2006, Oracle. All rights reserved. 3 - 30
Explicit Data Type Conversion
NUMBER
CHARACTER
TO_CHAR
TO_NUMBER
DATE
TO_CHAR
TO_DATE
Explicit Data Type Conversion (continued)
Function Purpose
TO_CHAR(number|date,[ fmt],
[nlsparams]) Date conversion: The nlsparams parameter specifies
the language in which month and day names and abbreviations are returned. If this parameter is omitted, this function uses the default date languages for the session.
TO_NUMBER(char,[fmt],
[nlsparams]) Converts a character string containing digits to a number
in the format specified by the optional format model fmt. The nlsparams parameter has the same purpose in this function as in the TO_CHAR function for number
Explicit Data Type Conversion (continued)
Note:The list of functions mentioned in this lesson includes only some of the available conversion functions.
Copyright © 2006, Oracle. All rights reserved. 3 - 32
Using the
TO_CHAR
Function with Dates
The format model:
•
Must be enclosed by single quotation marks
•
Is case sensitive
•
Can include any valid date format element
•
Has an
fm
element to remove padded blanks or
suppress leading zeros
•
Is separated from the date value by a comma
TO_CHAR(date, 'format_model')Displaying a Date in a Specific Format
Previously, all Oracle date values were displayed in the DD-MON-YY format. You can use the TO_CHARfunction to convert a date from this default format to one that you specify.
Guidelines
• The format model must be enclosed by single quotation marks and is case sensitive. • The format model can include any valid date format element. Be sure to separate the date
value from the format model by a comma.
• The names of days and months in the output are automatically padded with blanks. • To remove padded blanks or to suppress leading zeros, use the fill mode fmelement. • You can format the resulting character field with the iSQL*Plus COLUMNcommand
(covered in a later lesson).
SELECT employee_id, TO_CHAR(hire_date, 'MM/YY') Month_Hired FROM employees
Copyright © 2006, Oracle. All rights reserved. 3 - 33
Elements of the Date Format Model
Three-letter abbreviation of the day of the week
DY
Full name of the day of the week DAY
Two-digit value for month MM
Full name of the month MONTH
Three-letter abbreviation of the month MON
Numeric day of the month DD
Full year in numbers YYYY
Year spelled out (in English) YEAR
Result Element
Sample Format Elements of Valid Date Formats Element Description
SCC or CC Century; server prefixes B.C. date with - Years in dates YYYY or SYYYY Year; server prefixes B.C. date with - YYY or YY or Y Last three, two, or one digits of year Y,YYY Year with comma in this position
IYYY, IYY, IY, I Four-, three-, two-, or one-digit year based on the ISO standard
SYEAR or YEAR Year spelled out; server prefixes B.C. date with - BC or AD Indicates B.C. or A.D. year
B.C. or A.D. Indicates B.C. or A.D. year using periods Q Quarter of year
MM Month: two-digit value
MONTH Name of month padded with blanks to length of nine characters
MON Name of month, three-letter abbreviation RM Roman numeral month
WW or W Week of year or month DDD or DD or D Day of year, month, or week
DAY Name of day padded with blanks to a length of nine characters
DY Name of day; three-letter abbreviation
J Julian day; the number of days since December 31, 4713 B.C.
Copyright © 2006, Oracle. All rights reserved. 3 - 35
Elements of the Date Format Model
•
Time elements format the time portion of the date:
•
Add character strings by enclosing them in double
quotation marks:
•
Number suffixes spell out numbers:
DD "of" MONTH 12 of OCTOBERddspth fourteenth
HH24:MI:SS AM 15:45:32 PM
Date Format Elements: Time Formats
Use the formats that are listed in the following tables to display time information and literals and to change numerals to spelled numbers.
Element Description
AM or PM Meridian indicator
A.M. or P.M. Meridian indicator with periods
HH or HH12 or HH24 Hour of day, or hour (1–12), or hour (0–23) MI Minute (0–59)
Other Formats
Specifying Suffixes to Influence Number Display Element Description
/ . , Punctuation is reproduced in the result. “of the” Quoted string is reproduced in the result.
Element Description
TH Ordinal number (for example, DDTH for 4TH) SP Spelled-out number (for example, DDSP for FOUR) SPTH or THSP Spelled-out ordinal numbers (for example, DDSPTH for
Copyright © 2006, Oracle. All rights reserved. 3 - 37
SELECT last_name,
TO_CHAR(hire_date, 'fmDD Month YYYY') AS HIREDATE
FROM employees;
Using the
TO_CHAR
Function with Dates
…
Using the TO_CHARFunction with Dates
The SQL statement in the slide displays the last names and hire dates for all the employees. The hire date appears as 17 June 1987.
Example
Modify the slide example to display the dates in a format that appears as “Seventeenth of June 1987 12:00:00 AM.”
SELECT last_name, TO_CHAR(hire_date,
'fmDdspth "of" Month YYYY fmHH:MI:SS AM') HIREDATE
Copyright © 2006, Oracle. All rights reserved. 3 - 38
Using the
TO_CHAR
Function with Numbers
These are some of the format elements that you can use
with the
TO_CHAR
function to display a number value as a
character:
Prints a decimal point .
Prints a comma as thousands indicator ,
Places a floating dollar sign $
Uses the floating local currency symbol L
Represents a number 9
Forces a zero to be displayed 0
Result Element
TO_CHAR(number, 'format_model')
Using the TO_CHARFunction with Numbers
When working with number values such as character strings, you should convert those numbers to the character data type using the TO_CHARfunction, which translates a value of NUMBER data type to VARCHAR2data type. This technique is especially useful with concatenation.
Using the TO_CHARFunction with Numbers (continued)
Number Format Elements
If you are converting a number to the character data type, you can use the following format elements:
Element Description Example Result
9 Numeric position (number of 9s determine display width)
999999 1234 0 Display leading zeros 099999 001234 $ Floating dollar sign $999999 $1234 L Floating local currency symbol L999999 FF1234 D Returns in the specified position the decimal
character. The default is a period (.).
99D99 99.99 . Decimal point in position specified 999999.99 1234.00 G Returns the group separator in the specified
position. You can specify multiple group separators in a number format model.
9,999 9G999
, Comma in position specified 999,999 1,234 MI Minus signs to right (negative values) 999999MI 1234- PR Parenthesize negative numbers 999999PR <1234> EEEE Scientific notation (format must specify four Es) 99.999EEEE 1.234E+03 U Returns in the specified position the "Euro" (or
other) dual currency
U9999 €1234
V Multiply by 10 n times (n = number of 9s after V) 9999V99 123400 S Returns the negative or positive value S9999 -1234 or
+1234 B Display zero values as blank, not 0 B9999.99 1234.00
Copyright © 2006, Oracle. All rights reserved. 3 - 40
SELECT TO_CHAR(salary, '$99,999.00') SALARY FROM employees
WHERE last_name = 'Ernst';
Using the
TO_CHAR
Function with Numbers
Guidelines
• The Oracle server displays a string of number signs (#) in place of a whole number whose digits exceed the number of digits that is provided in the format model.
• The Oracle server rounds the stored decimal value to the number of decimal places that is provided in the format model.
Copyright © 2006, Oracle. All rights reserved. 3 - 41
Using the
TO_NUMBER
and
TO_DATE
Functions
•
Convert a character string to a number format
using the
TO_NUMBER
function:
•
Convert a character string to a date format using
the
TO_DATE
function:
•
These functions have an
fx
modifier. This modifier
specifies the exact matching for the character
argument and date format model of a
TO_DATE
function.
TO_NUMBER(char[, 'format_model'])
TO_DATE(char[, 'format_model'])
Using the TO_NUMBERand TO_DATEFunctions
You may want to convert a character string to either a number or a date. To accomplish this task, use the TO_NUMBERor TO_DATEfunctions. The format model that you choose is based on the previously demonstrated format elements.
The fxmodifier specifies exact matching for the character argument and date format model of a TO_DATEfunction:
• Punctuation and quoted text in the character argument must exactly match (except for case) the corresponding parts of the format model.
• The character argument cannot have extra blanks. Without fx, Oracle ignores extra blanks. • Numeric data in the character argument must have the same number of digits as the
Using the TO_NUMBERand TO_DATEFunctions (continued)
Example
Display the name and hire date for all employees who started on May 24, 1999. There are two spaces after the month Mayand the number 24in the following example. Because the fx modifier is used, an exact match is required and the spaces after the word Mayare not recognized:
SELECT last_name, hire_date FROM employees
WHERE hire_date = TO_DATE('May 24, 1999', 'fxMonth DD, YYYY'); *
WHERE hire_date = TO_DATE('May 24, 1999', 'fxMonth DD, YYYY') *
ERROR at line 3:
ORA-01858: a non-numeric character was found where a numeric was expected
Copyright © 2006, Oracle. All rights reserved. 3 - 43
RR
Date Format
Current Year 1995 1995 2001 2001 Specified Date 27-OCT-95 27-OCT-17 27-OCT-17 27-OCT-95 RR Format 1995 2017 2017 1995 YY Format 1995 1917 2017 2095 If two digits of the current year are: 0–49 0–49 50–99 50–99The return date is in the current century The return date is in the century after the current one
The return date is in the century before the current one The return date is in the current century If the specified two-digit year is:
RR
Date Format ElementThe RRdate format is similar to the YYelement, but you can use it to specify different centuries. Use the RRdate format element instead of YYso that the century of the return value varies according to the specified two-digit year and the last two digits of the current year. The table in the slide summarizes the behavior of the RRelement.
Current Year Given Date Interpreted (RR) Interpreted (YY)
1994 27-OCT-95 1995 1995 1994 27-OCT-17 2017 1917 2001 27-OCT-17 2017 2017
Copyright © 2006, Oracle. All rights reserved. 3 - 44
Example of
RR
Date Format
To find employees hired before 1990, use the
RR
date
format, which produces the same results whether the
command is run in 1999 or now:
SELECT last_name, TO_CHAR(hire_date, 'DD-Mon-YYYY') FROM employees
WHERE hire_date < TO_DATE('01-Jan-90','DD-Mon-RR');
Example of
RR
Date FormatTo find employees who were hired before 1990, the RRformat can be used. Because the current year is greater than 1999, the RRformat interprets the year portion of the date from 1950 to 1999.
The following command, on the other hand, results in no rows being selected because the YY format interprets the year portion of the date in the current century (2090).
SELECT last_name, TO_CHAR(hire_date, 'DD-Mon-yyyy') FROM employees
WHERE TO_DATE(hire_date, 'DD-Mon-yy') < '01-Jan-1990'; no rows selected
Copyright © 2006, Oracle. All rights reserved. 3 - 45
Nesting Functions
•
Single-row functions can be nested to any level.
•
Nested functions are evaluated from the deepest level
to the least deep level.
F3(
F2
(
F1(col,arg1)
,
arg2
),arg3)
Step 1 = Result
1
Step 2 = Result
2
Step 3 = Result 3
Nesting Functions
Single-row functions can be nested to any depth. Nested functions are evaluated from the innermost level to the outermost level. Some examples follow to show you the flexibility of these functions.
Copyright © 2006, Oracle. All rights reserved. 3 - 46
SELECT last_name,
UPPER(CONCAT(SUBSTR (LAST_NAME, 1, 8), '_US')) FROM employees
WHERE department_id = 60;
Nesting Functions
Nesting Functions (continued)
The slide example displays the last names of employees in department 60. The evaluation of the SQL statement involves three steps:
1. The inner function retrieves the first eight characters of the last name. Result1 = SUBSTR (LAST_NAME, 1, 8)
2. The outer function concatenates the result with _US. Result2 = CONCAT(Result1, '_US')
3. The outermost function converts the results to uppercase.
The entire expression becomes the column heading because no column alias was given.
Example
Display the date of the next Friday that is six months from the hire date. The resulting date should appear as Friday, August 13th, 1999. Order the results by hire date.
Copyright © 2006, Oracle. All rights reserved. 3 - 47
General Functions
The following functions work with any data type and
pertain to using nulls:
•
NVL (expr1, expr2)
•
NVL2 (expr1, expr2, expr3)
•
NULLIF (expr1, expr2)
•
COALESCE (expr1, expr2, ..., expr
n
)
General Functions
These functions work with any data type and pertain to the use of null values in the expression list.
Function Description
NVL Converts a null value to an actual value
NVL2 If expr1 is not null, NVL 2 returns ex pr2. If e xpr1 is null, NVL2
returns e xpr3. The argum ent exp r1 can have any data type.
NULLIF Com pares two expressions and returns null if they are equal; returns the first expression if they are not equal
Copyright © 2006, Oracle. All rights reserved. 3 - 48
NVL
Function
Converts a null value to an actual value:
•
Data types that can be used are date, character,
and number.
•
Data types must match:
–
NVL(commission_pct,0)
–
NVL(hire_date,'01-JAN-97')
–
NVL(job_id,'No Job Yet')
NVLFunction
To convert a null value to an actual value, use the NVL function.
Syntax
NVL (expr1, expr2) In the syntax:
• expr1is the source value or expression that may contain a null • expr2is the target value for converting the null
You can use the NVLfunction to convert any data type, but the return value is always the same as the data type of expr1.
NVLConversions for Various Data Types
Copyright © 2006, Oracle. All rights reserved. 3 - 49
SELECT last_name, salary, NVL(commission_pct, 0),
(salary*12) + (salary*12*NVL(commission_pct, 0)) AN_SAL FROM employees;
Using the
NVL
Function
…
1
1
2
2
Using the NVLFunction
To calculate the annual compensation of all employees, you need to multiply the monthly salary by 12 and then add the commission percentage to the result:
SELECT last_name, salary, commission_pct,
(salary*12) + (salary*12*commission_pct) AN_SAL FROM employees;
Copyright © 2006, Oracle. All rights reserved. 3 - 50
SELECT last_name, salary, commission_pct, NVL2(commission_pct,
'SAL+COMM', 'SAL') income
FROM employees WHERE department_id IN (50, 80);
Using the
NVL2
Function
1
2
2
1
Using the NVL2Function
The NVL2function examines the first expression. If the first expression is not null, then the NVL2function returns the second expression. If the first expression is null, then the third expression is returned.
Syntax
NVL2(expr1, expr2, expr3) In the syntax:
• expr1is the source value or expression that may contain null • expr2is the value that is returned if expr1is not null • expr3is the value that is returned if expr1is null
In the example shown in the slide, the COMMISSION_PCTcolumn is examined. If a value is detected, the second expression of SAL+COMMis returned. If the COMMISSION_PCTcolumn holds a null value, the third expression of SALis returned.
Copyright © 2006, Oracle. All rights reserved. 3 - 51
SELECT first_name, LENGTH(first_name) "expr1", last_name, LENGTH(last_name) "expr2",
NULLIF(LENGTH(first_name), LENGTH(last_name)) result FROM employees;
Using the
NULLIF
Function
…
1
2
3
1
2
3
Using the NULLIFFunction
The NULLIFfunction compares two expressions. If they are equal, the function returns null. If they are not equal, the function returns the first expression. You cannot specify the literal NULL for the first expression.
Syntax
NULLIF (expr1, expr2) In the syntax:
• expr1is the source value compared to expr2
• expr2is the source value compared with expr1(If it is not equal to expr1, expr1is returned.)
Copyright © 2006, Oracle. All rights reserved. 3 - 52
Using the
COALESCE
Function
•
The advantage of the
COALESCE
function over the
NVL
function is that the
COALESCE
function can
take multiple alternate values.
•
If the first expression is not null, the
COALESCE
function returns that expression; otherwise, it does
a
COALESCE
of the remaining expressions.
Using the COALESCEFunction
The COALESCE function returns the first non-null expression in the list.
Syntax
COALESCE (expr1, expr2, ... exprn) In the syntax:
• expr1returns this expression if it is not null
• expr2returns this expression if the first expression is null and this expression is not null • exprnreturns this expression if the preceding expressions are null
Copyright © 2006, Oracle. All rights reserved. 3 - 53 SELECT last_name, COALESCE(manager_id,commission_pct, -1) comm FROM employees ORDER BY commission_pct;
Using the
COALESCE
Function
…
Using the COALESCEFunction (continued)
In the example shown in the slide, if the MANAGER_IDvalue is not null, it is displayed. If the MANAGER_IDvalue is null, then the COMMISSION_PCTis displayed. If the MANAGER_ID and COMMISSION_PCTvalues are null, then the value –1 is displayed.
Copyright © 2006, Oracle. All rights reserved. 3 - 54
Conditional Expressions
•
Provide the use of IF-THEN-ELSE logic within a SQL
statement
•
Use two methods:
–
CASE
expression
–
DECODE
function
Conditional Expressions
Two methods used to implement conditional processing (IF-THEN-ELSE logic) in a SQL statement are the CASEexpression and the DECODEfunction.
Note:The CASEexpression complies with ANSI SQL. The DECODEfunction is specific to Oracle syntax.
Copyright © 2006, Oracle. All rights reserved. 3 - 55
CASE
Expression
Facilitates conditional inquiries by doing the work of an
IF-THEN-ELSE statement:
CASE expr WHEN comparison_expr1 THEN return_expr1 [WHEN comparison_expr2 THEN return_expr2 WHEN comparison_exprn THEN return_exprn ELSE else_expr]
END
CASEExpression
CASEexpressions let you use IF-THEN-ELSE logic in SQL statements without having to invoke procedures.
In a simple CASEexpression, the Oracle server searches for the first WHEN ... THENpair for which expris equal to comparison_exprand returns return_expr. If none of the WHEN ... THENpairs meet this condition, and if an ELSEclause exists, then the Oracle server returns else_expr. Otherwise, the Oracle server returns null. You cannot specify the literal NULLfor all the return_exprs and the else_expr.
All of the expressions ( expr, comparison_expr, and return_expr) must be of the same data type, which can be CHAR, VARCHAR2, NCHAR, or NVARCHAR2.
Copyright © 2006, Oracle. All rights reserved. 3 - 56
SELECT last_name, job_id, salary,
CASE job_id WHEN 'IT_PROG' THEN 1.10*salary WHEN 'ST_CLERK' THEN 1.15*salary WHEN 'SA_REP' THEN 1.20*salary ELSE salary END "REVISED_SALARY" FROM employees;
Using the
CASE
Expression
Facilitates conditional inquiries by doing the work of an
IF-THEN-ELSE statement:
…
…
Using the CASEExpression
In the SQL statement in the slide, the value of JOB_IDis decoded. If JOB_IDis IT_PROG, the salary increase is 10%; if JOB_IDis ST_CLERK, the salary increase is 15%; if JOB_IDis SA_REP, the salary increase is 20%. For all other job roles, there is no increase in salary. The same statement can be written with the DECODEfunction.
This is an example of a searched CASEexpression. In a searched CASEexpression, the search occurs from left to right until an occurrence of the listed condition is found, and then it returns the return expression. If no condition is found to be true, and if an ELSEclause exists, the return expression in the ELSEclause is returned; otherwise, NULLis returned.
SELECT last_name,salary,
(CASE WHEN salary<5000 THEN 'Low' WHEN salary<10000 THEN 'Medium' WHEN salary<20000 THEN 'Good' ELSE 'Excellent'
Copyright © 2006, Oracle. All rights reserved. 3 - 57
DECODE
Function
Facilitates conditional inquiries by doing the work of a
CASE
expression or an IF-THEN-ELSE statement:
DECODE(col|expression, search1, result1[, search2, result2,...,] [, default])
DECODEFunction
The DECODEfunction decodes an expression in a way similar to the IF-THEN-ELSE logic that is used in various languages. The DECODEfunction decodes expressionafter comparing it to each searchvalue. If the expression is the same as search, resultis returned.
If the default value is omitted, a null value is returned where a search value does not match any of the result values.
Copyright © 2006, Oracle. All rights reserved. 3 - 58
SELECT last_name, job_id, salary,
DECODE(job_id, 'IT_PROG', 1.10*salary, 'ST_CLERK', 1.15*salary, 'SA_REP', 1.20*salary, salary)
REVISED_SALARY FROM employees;
Using the
DECODE
Function
…
…
Using the DECODEFunction
In the SQL statement in the slide, the value of JOB_IDis tested. If JOB_IDis IT_PROG, the salary increase is 10%; if JOB_IDis ST_CLERK, the salary increase is 15%; if JOB_IDis SA_REP, the salary increase is 20%. For all other job roles, there is no increase in salary. The same statement can be expressed in pseudocode as an IF-THEN-ELSE statement:
IF job_id = 'IT_PROG' THEN salary = salary*1.10 IF job_id = 'ST_CLERK' THEN salary = salary*1.15 IF job_id = 'SA_REP' THEN salary = salary*1.20 ELSE salary = salary
Copyright © 2006, Oracle. All rights reserved. 3 - 59
SELECT last_name, salary,
DECODE (TRUNC(salary/2000, 0), 0, 0.00, 1, 0.09, 2, 0.20, 3, 0.30, 4, 0.40, 5, 0.42, 6, 0.44, 0.45) TAX_RATE FROM employees WHERE department_id = 80;
Using the
DECODE
Function
Display the applicable tax rate for each employee in
department 80:
Using the DECODEfunction (continued)
This slide shows another example using the DECODEfunction. In this example, you determine the tax rate for each employee in department 80 based on the monthly salary. The tax rates are as follows:
Monthly Salary Range Tax Rate
$0.00–1,999.99 00% $2,000.00–3,999.99 09% $4,000.00–5,999.99 20% $6,000.00–7,999.99 30% $8,000.00–9,999.99 40%
Copyright © 2006, Oracle. All rights reserved. 3 - 60
Summary
In this lesson, you should have learned how to:
•
Perform calculations on data using functions
•
Modify individual data items using functions
•
Manipulate output for groups of rows using
functions
•
Alter date formats for display using functions
•
Convert column data types using functions
•
Use
NVL
functions
•
Use IF-THEN-ELSE logic
Summary
Single-row functions can be nested to any level. Single-row functions can manipulate the following:
• Character data: LOWER, UPPER, INITCAP, CONCAT, SUBSTR, INSTR, LENGTH • Number data: ROUND, TRUNC, MOD
• Date data: MONTHS_BETWEEN, ADD_MONTHS, NEXT_DAY, LAST_DAY, ROUND, TRUNC Remember the following:
• Date values can also use arithmetic operators.
• Conversion functions can convert character, date, and numeric values: TO_CHAR, TO_DATE, TO_NUMBER
• There are several functions that pertain to nulls, including NVL, NVL2, NULLIF, and COALESCE.
• IF-THEN-ELSE logic can be applied within a SQL statement by using the CASEexpression or the DECODEfunction.
Copyright © 2006, Oracle. All rights reserved. 3 - 61
Practice 3: Overview of Part 2
This practice covers the following topics:
•
Creating queries that require the use of numeric,
character, and date functions
•
Using concatenation with functions
•
Writing non-case-sensitive queries to test the
usefulness of character functions
•
Performing calculations of years and months of
service for an employee
•
Determining the review date for an employee
Practice 3: Overview of Part 2
Part 2 of this lesson’s practice provides a variety of exercises using different functions that are available for character, number, and date data types. For Part 2, complete exercises 7–14.
Remember that for nested functions, the results are evaluated from the innermost function to the outermost function.
…
Practice 3Part 1
1. Write a query to display the current date. Label the column Date.
2. The HR department needs a report to display the employee number, last name, salary, and salary increased by 15.5% (expressed as a whole number) for each employee. Label the column New Salary. Place your SQL statement in a text file named lab_03_02.sql.
3. Run your query in the file lab_03_02.sql.
4. Modify your query lab_03_02.sqlto add a column that subtracts the old salary from the new salary. Label the column Increase. Save the contents of the file as
lab_03_04.sql. Run the revised query.
Practice 3 (continued)
5. Write a query that displays the last name (with the first letter uppercase and all other letters lowercase) and the length of the last name for all employees whose name starts with the letters J, A,or M. Give each column an appropriate label. Sort the results by the employees’ last names.
Rewrite the query so that the user is prompted to enter a letter that starts the last name. For example, if the user enters
H
when prompted for a letter, then the output should show all employees whose last name starts with the letter H.Practice 3 (continued)
6. The HR department wants to find the length of employment for each employee. For each employee, display the last name and calculate the number of months between today and the date on which the employee was hired. Label the column MONTHS_WORKED. Order your results by the number of months employed. Round the number of months up to the closest whole number.
Practice 3 (continued)
Part 2
7. Create a report that produces the following for each employee:
<employee last name> earns <salary> monthly but wants <3 times salary>. Label the column Dream Salaries.
If you have time, complete the following exercises:
8. Create a query to display the last name and salary for all employees. Format the salary to be 15 characters long, left-padded with the $ symbol. Label the column SALARY.
…
Practice 3 (continued)
9. Display each employee’s last name, hire date, and salary review date, which is the first Monday after six months of service. Label the column REVIEW. Format the dates to appear in the format similar to “Monday, the Thirty-First of July, 2000.”
10. Display the last name, hire date, and day of the week on which the employee started. Label the column DAY. Order the results by the day of the week, starting with Monday.
…
Practice 3 (continued)
If you want an extra challenge, complete the following exercises:
11. Create a query that displays the employees’ last names and commission amounts. If an employee does not earn commission, show “No Commission.” Label the column COMM.
12. Create a query that displays the first eight characters of the employees’ last names and indicates the amounts of their salaries with asterisks. Each asterisk signifies a thousand dollars. Sort the data in descending order of salary. Label the column
EMPLOYEES_AND_THEIR_SALARIES.
…
Practice 3 (continued)
13. Using the DECODEfunction, write a query that displays the grade of all employees based on the value of the column JOB_ID, using the following data:
Job Grade AD_PRES A ST_MAN B IT_PROG C SA_REP D ST_CLERK E