SQL Functions
SQL Functions
The TO_NUMBER function converts a character value to a numeric datatype. If the string being
converted contains nonnumeric characters, the function returns an error.
SQL> select to_number('123') from dual;
TO_NUMBER('123')
----------------
123
SQL> select to_number('one') from dual;
select to_number('one') from dual
*
ERROR at line 1:
ORA-01722: invalid number
2) TO_DATE function
The function takes character values as input and returns formatted date equivalent of the same.
The TO_DATE function allows users to enter a date in any format, and then it converts the entry
into the default format
SQL> select to_date('01-mar-21') from dual;
TO_DATE('
---------
01-MAR-21
TO_CHAR function
TO_CHAR function is used to conver a numeric or date input to character type with a different
formats
SQL> select to_char(sal,'$9999.99') from emp;
TO_CHAR(S
---------
$800.00
$1600.00
$1250.00
$2975.00
$1250.00
eg:
MM - Month of year 01, 02...12
- Month in characters (i.e.
MONTH
January)
MON - JAN, FEB
Day of year in numbers (i.e.
DDD -
365)
Day of the month in numbers
DD -
(i.e. 28)
Day of week in numbers(i.e.
D -
7)
YEAR - Year in characters
YY - Year with 2 numbers
YYYY - Year with 4 numbers
Week number of the
WW -
year(i.e. 1)
Week number of the month
W -
(i.e. 5)
SP- Spelled format
TH- ST,ND,RD,TH
Hour number of the day (1-
HH -
12)
Hour number of the day with
HH24-
24Hours notation (0-23)
AM, PM - AM or PM
Number of minutes and
MI, SS-
seconds
Day of the week in
DAY -
characters (i.e. Monday)
Day of the week in short
DY - character description (i.e.
SUN)
General Functions
NVL(Null Values)
The NVL function substitutes an alternate value for a NULL value.
Syntax: NVL(arg1,arg2)
If 1st argument is null it returns 2nd argument
If 1st argument is not null it returns 1st argument
Eg:Display total salary (sal+comm) of emp
SQL> select ename,sal,comm,sal+nvl(comm,0) "Total_Sal" from
emp;
ENAME SAL COMM Total_Sal
---------- ---------- ---------- ----------
SMITH 800 800
ALLEN 1600 300 1900
WARD 1250 500 1750
JONES 2975 2975
2) NVL2
As an enhancement over NVL
NVL2 function can be used to substitute an alternate value for
NULL as well as non NULL value.
Syntax:
NVL2( string1, value_if_NOT_null, value_if_null )
Eg: WAQTD total sal (sal+comm) of all emp and give commission
Rs. 100 to all emp
SQL> select ename,sal,comm,sal+NVL2(comm,comm+100,100)
from emp;
ENAME SAL COMM
SAL+NVL2(COMM,COMM+100,100)
---------- ---------- ---------- ---------------------------
SMITH 800 900
ALLEN 1600 300 2000
WARD 1250 500 1850
JONES 2975 3075
NULLIF
------
SUNDAY
SQL> select nullif('SUNDAY','SUNDAY') from dual;
NULLIF
------
6). COALESCE
COALESCE function is similar NVL, returns the first not-null expression in the argument list. It
takes minimum two mandatory parameters but maximum arguments has no limit.
Syntax:
COALESCE (expr1, expr2, ... expr_n )
SQL> select COALESCE(null,null,'A') from dual;
C
-
A
C
-
A