0% found this document useful (0 votes)
8 views

SQL Fundamentals Lesson#5 Functions Single Row II CH#5 Day 06 07

This document covers SQL conversion functions, specifically focusing on TO_CHAR, TO_NUMBER, and TO_DATE, which are used to convert data types in SQL. It explains implicit and explicit data type conversions, provides examples of using these functions, and introduces general functions for handling null values. Additionally, it discusses conditional expressions using CASE and DECODE functions to implement IF-THEN-ELSE logic in SQL statements.

Uploaded by

Samaneh Eivani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

SQL Fundamentals Lesson#5 Functions Single Row II CH#5 Day 06 07

This document covers SQL conversion functions, specifically focusing on TO_CHAR, TO_NUMBER, and TO_DATE, which are used to convert data types in SQL. It explains implicit and explicit data type conversions, provides examples of using these functions, and introduces general functions for handling null values. Additionally, it discusses conditional expressions using CASE and DECODE functions to implement IF-THEN-ELSE logic in SQL statements.

Uploaded by

Samaneh Eivani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Page 1 of 24

SQL Fundamentals
Lesson#5 -
Single Row functions - Conversion Functions

Objectives

• Describe the various types of conversion functions that are available in SQL
• Use the TO_CHAR, TO_NUMBER, and TO_DATE conversion functions
• Apply conditional expressions in a SELECTstatement
Page 2 of 24

Conversion Functions

In addition to Oracle data types, columns of tables in an Oracle Database can be


defined by using the American National Standards Institute (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 receives 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
implicitly by the Oracle server or explicitly by the user.
Implicit data type conversions work according to the rules explained in the following
slides.

Explicit data type conversions are performed 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 datatypeTOdatatype. The first data
type is the input data type and the second data type is the output.
Page 3 of 24

Implicit Data Type Conversion

In expressions, the Oracle server can automatically convert the


following:

From To
VARCHAR2 or CHAR NUMBER
VARCHAR2 or CHAR DATE
Page 4 of 24

Implicit Data Type Conversion

For expression evaluation, the Oracle server can automatically convert


the following:

From To
NUMBER VARCHAR2 or CHAR
DATE VARCHAR2 or CHAR
Page 5 of 24

Explicit Data Type Conversion


Page 6 of 24

Using the TO_CHARFunction with Dates

TO_CHAR(date[,'format_model'])

The format model:


• Must be enclosed within 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
Page 7 of 24

Elements of the Date Format Model

Element Result
YYYY Full year in numbers
YEAR Year spelled out (in English)
MM Two-digit value for the month
MONTH Full name of the month
MON Three-letter abbreviation of the month
DY Three-letter abbreviation of the day of the week
DAY Full name of the day of the week
DD Numeric day of the month
Page 8 of 24

Elements of the Date Format Model

• Time elements format the time portion of the date:

HH24:MI:SS AM 15:45:32 PM

• Add character strings by enclosing them within double


quotation marks:

DD "of" MONTH 12 of OCTOBER

• Number suffixes spell out numbers:

ddspth fourteenth
Page 9 of 24

Using the TO_CHARFunction with Dates

SELECT last_name,

TO_CHAR(hire_date, 'fmDD Month YYYY')


AS HIREDATE

FROM employees;
Page 10 of 24

Using the TO_CHARFunction with Numbers

TO_CHAR(number[, 'format_model'])

These are some of the format elements that you can use with the
TO_CHAR function to display a number value as a character:

Element Result
9 Represents a number
0 Forces a zero to be displayed
$ Places a floating dollar sign
L Uses the floating local currency symbol
. Prints a decimal point
, Prints a comma as a thousands indicator
Page 11 of 24

Using the TO_NUMBERand TO_DATEFunctions

• Convert a character string to a number format using the


TO_NUMBERfunction:

TO_NUMBER(char[, 'format_model'])

• Convert a character string to a date format using the


TO_DATEfunction:

TO_DATE(char[, 'format_model'])
• These functions have an fx modifier. This modifier specifies the exact
match for the character argument and date format model of a TO_DATE
function.

You may want to convert a character string to either a number or a date. To


accomplish this task, use the TO_NUMBER or TO_DATE functions. The format
model that you select is based on the previously demonstrated format elements.
The fx modifier specifies the exact match 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, the Oracle
server ignores extra blanks.
• Numeric data in the character argument must have the same number of digits
as the corresponding element in the format model. Without fx, the numbers in the
character argument can omit leading zeros.
Page 12 of 24

Example
Display the name and hire date for all employees who started on May 24, 2007. There
are two spaces after the month May and before the number 24 in the following
example. Because the fx modifier is used, an exact match is required and the spaces
after the word May are not recognized:
SELECT last_name, hire_date
FROM employees
WHERE hire_date = TO_DATE('May 24, 2007', 'fxMonth DD, YYYY');
The resulting error output looks like this:

To see the output, correct the query by deleting the extra space between ‘May’ and ‘24’.

SELECT last_name, hire_date


FROM employees
WHERE hire_date = TO_DATE('May 24, 2007', 'fxMonth DD, YYYY');
Page 13 of 24

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, ...,exprn)
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, NVL2 returns expr2. If expr1 is null, NVL2
returns expr3. The argument expr1can have any data type.
NULLIF Compares two expressions and returns null if they are equal;
returns the first expression if they are not equal
COALESCE Returns the first non-null expression in the expression list
Page 14 of 24

NVLFunction

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')
Page 15 of 24

Using the NVL2Function

SELECT last_name, salary, commission_pct, 1


NVL2(commission_pct,
'SAL+COMM', 'SAL') income 2
FROM employees WHERE department_id IN (50, 80);

1 2
Page 16 of 24

Using the NULLIFFunction

SELECT first_name, LENGTH(first_name) "expr1",


last_name, LENGTH(last_name) "expr2", 2
NULLIF(LENGTH(first_name), LENGTH(last_name)) result 3
FROM employees;


1 2 3
Page 17 of 24

Using the COALESCE Function

• The advantage of the COALESCE function over the NVL


function is that the COALESCE function can take multiple
alternative values.
• If the first expression is not null, the COALESCE function returns
that expression; otherwise, it does a COALESCE of the
remaining expressions.
Page 18 of 24

Using the COALESCEFunction

SELECT last_name, salary, commission_pct,


COALESCE((salary+(commission_pct*salary)), salary+2000)"New Salary"
FROM employees;
Page 19 of 24

Conditional Expressions

• Provide the use of the IF-THEN-ELSE logic within a SQL


statement
• Use the following methods:
– CASEexpression
– Searched CASEexpression
– DECODEfunction
Page 20 of 24

CASEExpression

Facilitates conditional inquiries by doing the work of an


IF-THEN-ELSEstatement:

CASE expr WHEN comparison_expr1 THEN return_expr1


comparison_expr2
[WHEN THEN return_expr2
comparison_exprn
WHEN
ELSE else_expr] THEN return_exprn

END

CASEexpressions allow you to use the IF-THEN-ELSElogic in SQL statements


without having to invoke procedures.

In a simple CASE expression, the Oracle server searches for the first WHEN ... THEN
pair for which expr is equal to comparison_expr and returns return_expr. If none of the
WHEN ... THEN pairs meet this condition, and if an ELSE clause exists, the Oracle
server returns else_expr. Otherwise, the Oracle server returns a null. You cannot
specify the literal NULLfor all the return_exprs and the else_expr.

The expressions exprand comparison_exprmust be of the same data type, which can be
CHAR, VARCHAR2, NCHAR, or NVARCHAR2,NUMBER,BINARY_FLOAT, or
BINARY_DOUBLEor
must all have a numeric data type. All of the return values (return_expr) must be of the
same data type.
Page 21 of 24

Using the CASEExpression

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;
Page 22 of 24

Searched CASEExpression

CASE

WHEN condition1 THEN use_expression1


WHEN condition2 THEN use_expression2
WHEN condition3 THEN use_expression3
ELSE default_use_expression

END
SELECT last_name,salary,

(CASE WHEN salary<5000 THEN 'Low'

WHEN salary<10000 THEN 'Medium'


WHEN salary<20000 THEN 'Good'
ELSE 'Excellent'

END) qualified_salary
FROM employees;
Page 23 of 24

DECODEFunction

Facilitates conditional inquiries by doing the work of a CASE


expression or an IF-THEN-ELSEstatement:

The DECODEfunction decodes an expression in a way similar to the IF-THEN-


ELSElogic that is used in various languages. The DECODE function decodes
expression after 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.
Page 24 of 24

Using the DECODEFunction

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;

END ---------------------------------

You might also like