SQL Functions
SQL Functions
Dual
Oracle provides a special table named, DUAL, which can be used to test any
function. It is a small oracle worktable, which consists of only one row and one
column, and contains the value x in that column.
Character Functions:
Character functions are used primarily to modify character columns.
LTRIM: It removes characters from the left of character with initial characters
removed upto the first character not in set.
Syntax : LTRIM (‘string’,’set’);
Example : SELECT LTRIM (‘xxxXxxRAMESH’,’x’) FROM DUAL;
Output : XxxRAMESH
RTRIM: It returns character, with final characters removed after the last character
not in the set. Set is optional
Syntax : RTRIM (‘character’,’set’);
Example : SELECT RTRIM (‘RAMESHxxXxx’,’x’) FROM DUAL;
Output : RAMESHxxX
CHR : It convert ASCII values into characters.
Syntax : CHR (string);
Example : SELECT CHR (169) FROM DUAL;
Output : A
NUMBER FUNCTIONS:
ABS : It returns the absolute value of data (i.e. positive
value)
Syntax : ABS (data);
Example : SELECT ABS (-5000) FROM DUAL;
Output : 5000
AGGREGATE FUNCTIONS:
AVG : It returns average value of n, ignoring null values
Syntax : AVG ([DISTINCT|ALL] n);
Example : SELECT AVG (rate) FROM ITEM_MASTER;
COUNT(*) : It returns the number of rows in the table including duplicates and
those with null.
Syntax : COUNT (*);
Example : SELECT COUNT (*) FROM STUDENT;
DATE FUNCTION:
Consider the date 15-Jan-98
ADD_MONTHS : To add months to one date to get another.
Syntax : ADD_MONTHS (date,value);
Example : SELECT ADD_MONTHS (’15-JAN-98’,5) FROM
DUAL;
Output : 15-JAN-98
CONVERSION FUNCTIONS:
TO_CHAR: TO_CHAR function can be used to convert a date
or number to a character stiring.
Syntax : TO_CHAR (n[,fmt]);
With the TO_CHAR function, a date item can be formatted many ways. The format
must be enclosed within single quotes. Consider 19-AUG-96 as the system date,
then.
Example : SELECT TO_CHAR (SYSDATE,’MONTH’) FROM
DUAL;
Output : August
Example : SELECT TO_CHAR (SYSDATE,’dd/mm/yyyy’) FROM DUAL;
Output : 19/08/1996
OTHER FUNCTIONS:
NVL : The NVL function is used to substitute any NULL
value with a user specified value.
Syntax : NVL (x,expression);
Example : SELECT EMP_NO,ENAME,NVL(COMM,200) FROM
DUAL;
Q. Write a query in SQL whose sal>1500 then the commission is 200.
Q. Write a query in SQL whose emp_no=1001 then the commission will be null.
DECODE: The DECODE function can be used to expand any abbreviations used in
the table.
Q. PATNA has been coded as PAT, RANCHI as RAN, JAMSHEDPUR a JAM, BOKARO
as BOK, in the column, city of the customer table.
Example : SELECT CITY, DECODE (CITY,’PAT’, ’PATNA’, ’RAN’,
’RANCHI’,’JAM’,’JAMSHEDPU’,’BOK’,’BOKARO’,’NOT SPECIFIED’)”CITY NAME” FROM
CUSTOMER;