Slide 10 - General Functions
Slide 10 - General Functions
4
• Nesting functions
Using General Functions and • General functions:
– NVL
Conditional Expressions
– NVL2
– NULLIF
– COALESCE
• Conditional expressions:
– CASE
– DECODE
Copyright © 2009, Oracle. All rights reserved. 4-2 Copyright © 2009, Oracle. All rights reserved.
The following functions work with any data type and pertain to Converts a null value to an actual value:
using nulls: • Data types that can be used are date, character, and
• NVL (expr1, expr2) number.
• NVL2 (expr1, expr2, expr3) • Data types must match:
• NULLIF (expr1, expr2) – NVL(commission_pct,0)
• COALESCE (expr1, expr2, ..., exprn) – NVL(hire_date,'01-JAN-97')
– NVL(job_id,'No Job Yet')
4-3 Copyright © 2009, Oracle. All rights reserved. 4-4 Copyright © 2009, Oracle. All rights reserved.
… 2
1 2 1
4-5 Copyright © 2009, Oracle. All rights reserved. 4-6 Copyright © 2009, Oracle. All rights reserved.
Using the NULLIF Function Using the COALESCE Function
1
• The advantage of the COALESCE function over the NVL
SELECT first_name, LENGTH(first_name) "expr1", function is that the COALESCE function can take multiple
last_name, LENGTH(last_name) "expr2", 2 alternate values.
NULLIF(LENGTH(first_name), LENGTH(last_name)) result 3 • If the first expression is not null, the COALESCE function
FROM employees;
returns that expression; otherwise, it does a COALESCE of
the remaining expressions.
1 2 3
4-7 Copyright © 2009, Oracle. All rights reserved. 4-8 Copyright © 2009, Oracle. All rights reserved.
…
4-9 Copyright © 2009, Oracle. All rights reserved. 4 - 10 Copyright © 2009, Oracle. All rights reserved.
• Provide the use of the IF-THEN-ELSE logic within a SQL Facilitates conditional inquiries by doing the work of an
statement IF-THEN-ELSE statement:
• Use two methods:
CASE expr WHEN comparison_expr1 THEN return_expr1
– CASE expression
[WHEN comparison_expr2 THEN return_expr2
– DECODE function WHEN comparison_exprn THEN return_exprn
ELSE else_expr]
END
4 - 11 Copyright © 2009, Oracle. All rights reserved. 4 - 12 Copyright © 2009, Oracle. All rights reserved.
Using the CASE Expression DECODE Function
Facilitates conditional inquiries by doing the work of an Facilitates conditional inquiries by doing the work of a CASE
IF-THEN-ELSE statement: expression or an IF-THEN-ELSE statement:
SELECT last_name, job_id, salary,
CASE job_id WHEN 'IT_PROG' THEN 1.10*salary DECODE(col|expression, search1, result1
WHEN 'ST_CLERK' THEN 1.15*salary [, search2, result2,...,]
WHEN 'SA_REP' THEN 1.20*salary [, default])
ELSE salary END "REVISED_SALARY"
FROM employees;
…
4 - 13 Copyright © 2009, Oracle. All rights reserved. 4 - 14 Copyright © 2009, Oracle. All rights reserved.
4 - 15 Copyright © 2009, Oracle. All rights reserved. 4 - 16 Copyright © 2009, Oracle. All rights reserved.
Summary