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

SQL_Fns

The document provides an overview of Oracle SQL functions, categorized into single row functions, group functions, character functions, conversion functions, and date functions. It includes detailed descriptions and examples of various mathematical, character, and date operations that can be performed using SQL. Additionally, it discusses how to alter session settings for date formats and the use of the RR date format element for century flexibility.

Uploaded by

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

SQL_Fns

The document provides an overview of Oracle SQL functions, categorized into single row functions, group functions, character functions, conversion functions, and date functions. It includes detailed descriptions and examples of various mathematical, character, and date operations that can be performed using SQL. Additionally, it discusses how to alter session settings for date formats and the use of the RR date format element for century flexibility.

Uploaded by

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

Oracle SQL Functions

The Oracle implementation of SQL provides a number of functions that can be used in SELECT statements.
Functions are typically grouped into the following:

 Single row functions - Operate on column values for each row returned by a query.
 Group functions - Operate on a collection (group) of rows (already discussed).

The following is an overview and brief description of single row functions. x is some number, s is a string of
characters and c is a single character. For illustration we use DUAL pseudo column but it may be applied on
any appropriate column or expression.

 Math functions include:

ABS (x) Absolute Value of x


CEIL (x) Smallest integer greater than or equal to x.
COS (x) Cosine of x
FLOOR (x) Largest integer less than or equal to x.
LOG (x) Log of x
LN (x) Natural Log of x
ROUND (x, n) Round x to n decimal places to the right of the decimal point.
SIN (x) Sine of x
TAN (x) Tangent of x
TRUNC (x, n) Truncate x to n decimal places to the right of the decimal point.

Illustration:

SELECT ABS(-15) "Absolute" FROM DUAL; SELECT CEIL(15.7) "Ceiling" FROM DUAL;

Absolute Ceiling
---------- ----------
15 16
SELECT FLOOR(15.7) "Floor" SELECT MOD(11,4) "Modulus"
FROM DUAL; FROM DUAL;

Floor Modulus
---------- ----------
15 3
SELECT POWER(3,2) "Raised" SELECT ROUND(15.193,1) "Round"
FROM DUAL FROM DUAL;
Raised
---------- Round
9 ----------
15.2
SELECT ROUND(15.193,-1) "Round" SELECT TRUNC(15.79,1) "Truncate"
FROM DUAL FROM DUAL
Round Truncate
---------- ----------
20 15.7
SELECT TRUNC(15.79,-1) "Truncate"
FROM DUAL
Truncate
----------
10
1
Compiled by Manas Ghosh
 Character functions include:

CHR (x) Character for ASCII value x.


INITCAP (s) String s with the first letter of each word capitalized.
LOWER (s) Converts string s to all lower case letters.
LPAD (s, x) Pads string s with x spaces to the left.
LTRIM (s) Removes leading spaces from s.
REPLACE (s1, s2, s3) Replace occurrences of s2 with s3 in string s1.
RPAD (s, x) Pads string s with x spaces to the right.
RTRIM (s) Removes trailing spaces from s.
SUBSTR (s, x1, x2) Return a portion of string s starting at position x1 and ending with
position x2. If x2 is omitted, it's value defaults to the end of s.
UPPER (s) Converts string s to all upper case letters.
s1 || s2 (two vertical bars or "pipe" symbols) Concatenates s1 with s2

 C h a r a c t e r f u n c t i o n s t h a t r e t u r n n u mb e r s i n c l u d e :

ASCII (c) Returns the ASCII value of c


INSTR (s1, s2, x) Returns the position of s2 in s1 where the search starts at position x.
LENGTH (s) Length of s

Illustration:

SELECT CHR(67)||CHR(65)||CHR(84) "Dog" FROM DUAL;

Dog
---
CAT

SELECT CONCAT( CONCAT(ename, ' is a '), desg) "Job" FROM emp


WHERE empno = ‘E01’

Job
-----------------
RAJA SEN is a CLERK

SELECT LOWER('MR. RAJA SEN') "Lowercase" FROM DUAL

Lowercase
--------------------
mr. raja sen

SELECT LPAD('Page 1',15,'*.') "LPAD example" FROM DUAL

LPAD example
---------------
*.*.*.*.*Page 1

SELECT SUBSTR('ABCDEFG',3.1,4) "Subs" FROM DUAL

Subs
----
CDEF

2
Compiled by Manas Ghosh
SELECT SUBSTR('ABCDEFG',-5,4) "Subs" FROM DUAL

Subs
----
CDEF

SELECT INSTR('CORPORATE FLOOR','OR', 3, 2) "Instring" FROM DUAL


Instring
----------
14

SELECT LENGTH('CANDIDE') "Length in characters" FROM DUAL

Length in characters
--------------------
7

 Conversion functions include:

TO_CHAR (date, format) Converts a date column to a string of characters. format is a set
of Date formatting codes where:

YYYY is a 4 digit year.


MM is a month number.
MONTH is the full name of the month.
MON is the abbreviated month.
DDD is the day of the year.
DD is the day of the month.
D is the day of the week.
DAY is the name of the day.
HH is the hour of the day (12 hour clock)
HH24 is the hour of the day (24 hour clock)
MI is the minutes.
SS is the seconds.

TO_CHAR (number, format) Converts a numeric column to a string of characters. format is a


set of number formatting codes where:
9 indicates a digit position.
Blank if position value is 0.
0 indicates a digit position. Shows a 0 if the position value is 0.
$ displays a leading currency indicator.
TO_DATE (s, format) Converts a character column (string s to a date. format is a set of
Date formatting codes as above.
TO_NUMBER (s, format) Converts a character column (string s to a Number. format is a
set of Number formatting codes as above.

Illustration:

SELECT TO_CHAR(SYSDATE, '"Today is" Day') FROM DUAL;

TO_CHAR(SYSDATE,'"
------------------
Today is Friday

SELECT TO_CHAR(SYSDATE, 'DD/MM/YY') FROM DUAL;

TO_CHAR
--------
3
Compiled by Manas Ghosh
25/03/05

SELECT TO_CHAR(SYSDATE, 'DD-MM-YYYY') FROM DUAL;

TO_CHAR(SY
----------
25-03-2005

SELECT TO_CHAR(SYSDATE, 'YYYY') FROM DUAL;


TO_C
----
2005

SELECT TO_CHAR (TO_DATE (’22-FEB-05’), ‘Day’) FROM DUAL;

TO_CHAR(T
---------
Tuesday

TO_DATE can also accept numbers without single quotient mark provided they are
formatted properly.

SELECT TO_DATE (11051995, ‘MMDDYYYY’) FROM DUAL;

TO_DATE(1
---------
05-NOV-95

Let us apply these conversion functions for querying EMP table.

 Query: List date of join of each employee in ‘DD/MM/YYYY’ format with code, name.

SELECT ecode, ename, TO_CHAR(dt_jn,'DD/MM/YYYY') FROM emp;

 List employees information who have joined after 31/12/1996

SELECT * FROM emp WHERE dt_jn>TO_DATE('31/12/1996','DD/MM/YYYY')

 Calculate Employment length of each employee

SELECT ecode, ename,


TO_CHAR((SYSDATE – dt_jn) / 365, '99') As Employment_Length
FROM emp;

 Date functions include:

Returns the date d plus n months. The argument n can be any integer. If d is
the last day of the month or if the resulting month has fewer days than the day
ADD_MONTHS(d,n)
component of d, then the result is the last day of the resulting month.
Otherwise, the result has the same day component as d.
Returns the date of the last day of the month that contains d. You might use
LAST_DAY(d)
this function to determine how many days are left in the current month.
Returns number of months between dates d1 and d2. If d1 is later than d2,
MONTHS_BETWEEN(d1,d2)
result is positive; if earlier, negative. If d1 and d2 are either the same days of

4
Compiled by Manas Ghosh
the month or both last days of months, the result is always an integer;
otherwise ORACLE calculates the fractional portion of the result based on a
31-day month and also considers the difference in time components of d1 and
d2.
Returns the date of the first weekday named by char that is later than the date
d. The argument char must be a day of the week in your session's date
NEXT_DAY(d,char)
language. The return value has the same hours, minutes, and seconds
component as the argument d.
Returns the current date and time. Requires no arguments. In distributed SQL
SYSDATE statements, this function returns the date and time of your local database.
You cannot use this function in the condition of a CHECK constraint.

How does one add a day/hour/minute/second to a date value?

The SYSDATE pseudo-column shows the current system date and time. Adding 1 to SYSDATE
will advance the date by 1 day. Use fractions to add hours, minutes or seconds to the date. Look
at these examples:
select sysdate, sysdate+1/24, sysdate +1/1440, sysdate +
1/86400 from dual;

SYSDATE SYSDATE+1/24 SYSDATE+1/1440


SYSDATE+1/86400
-------------------- -------------------- --------------------
--------------------
03-Jul-2002 08:32:12 03-Jul-2002 09:32:12 03-Jul-2002 08:33:12
03-Jul-2002 08:32:13

The following format is frequently used with Oracle Replication:


select sysdate NOW, sysdate+30/(24*60*60) NOW_PLUS_30_SECS from dual;

NOW NOW_PLUS_30_SECS
-------------------- --------------------
03-JUL-2002 16:47:23 03-JUL-2002 16:47:53

Here are a couple of examples:

Description Date Expression


Now SYSDATE
Tomorow/ next day SYSDATE + 1
Seven days from now SYSDATE + 7
One hour from now SYSDATE + 1/24
Three hours from now SYSDATE + 3/24
An half hour from now SYSDATE + 1/48
10 minutes from now SYSDATE + 10/1440
30 seconds from now SYSDATE + 30/86400
Tomorrow at 12 midnight TRUNC(SYSDATE + 1)
Tomorrow at 8 AM TRUNC(SYSDATE + 1) + 8/24
Next Monday at 12:00
NEXT_DAY(TRUNC(SYSDATE), 'MONDAY') + 12/24
noon
First day of next month at
TRUNC(LAST_DAY(SYSDATE ) + 1)
12 midnight
First day of the current
TRUNC(LAST_DAY(ADD_MONTHS(SYSDATE,-1))) + 1
month
The next Monday, TRUNC(LEAST(NEXT_DAY(sysdate,''MONDAY''

5
Compiled by Manas Ghosh
Wednesday or Friday at 9 ),NEXT_DAY(sysdate,''WEDNESDAY''), NEXT_DAY(sysdate,''FRIDAY'' ))) +
a.m (9/24)

Illustration:

SELECT TO_CHAR(ADD_MONTHS(dt_jn,1), 'DD-MON-YYYY') "Next month"


FROM emp WHERE ename = 'SMITH';

Next Month
-----------
17-JAN-1981

SELECT SYSDATE,LAST_DAY(SYSDATE) "Last",


LAST_DAY(SYSDATE) - SYSDATE "Days Left" FROM DUAL;

SYSDATE Last Days Left


--------- --------- ---------
10-APR-95 30-APR-95 20

SELECT MONTHS_BETWEEN(TO_DATE('02-02-1995','MM-DD-YYYY'),
TO_DATE('01-01-1995','MM-DD-YYYY') ) "Months" FROM DUAL;

Months
----------
1.03225806

SELECT NEXT_DAY('15-MAR-92','TUESDAY') "NEXT DAY" FROM DUAL;

NEXT DAY
---------
17-MAR-92

SELECT TO_CHAR(SYSDATE, 'MM-DD-YYYY HH24:MI:SS') “NOW” FROM DUAL

NOW
--------------------
10-29-1993 20:27:11.

The following statement selects the dates that each employee from department 20 was hired and uses the
TO_CHAR function to convert these dates to character strings with the format specified by the date format
model 'fmMonth DD, YYYY':

SELECT ename, TO_CHAR(dt_jn,'fmMonth DD, YYYY') “Date of Join”


FROM emp WHERE deptno = 20

ENAME Date of Join


-------- -----------------
PETERS December 17, 1980
ALBERS April 2, 1981
SATO April 19, 1987
MAKI May 23, 1987
FORD December 3, 1981

With this format model, Oracle returns the hire dates with the month spelled out, two digits for the day, and
the century included in the year.

6
Compiled by Manas Ghosh
Text, dates and numbers can be combined using the various conversion functions. In the following example,
the TO_CHAR function is used to convert the date column ‘dob’ into a character string.

SELECT 'The oldest employee was born on '


||TO_CHAR( MIN(dob), 'DD/MM/YYYY') AS Sentence FROM emp;

SENTENCE
----------------------------------------
The oldest employee was born on 10/11/1927

Date math results in a numerical answer that must be converted to characters to concatenate with other
character strings as in this next example:

SELECT 'The oldest employee was born on ' ||


TO_CHAR( MIN(bdate), 'DD/MM/YYYY') || ' and is now' ||
TO_CHAR( (SYSDATE - MIN(bdate)) / 365, '99') ||
' years old.' AS Sentence
FROM emp;

SENTENCE
-----------------------------------------------------------------
The oldest employee was born on 10/11/1927 and is now 70 years old.

Using the ALTER SESSION Statement for Date Formats

In the previous examples of SQL statements, the default format of data of type DATE has been in the form:
DD-MON-YY

The TO_CHAR and TO_DATE functions can be used to convert dates to other formats, however, this may
become inconvenient, especially when inserting a large number of rows.

The ALTER SESSION statement can be used to alter various characteristics of the current SQL*Plus
session including the default date format. This statement is often used to format dates to conform to regional
customs. The syntax of ALTER SESSION for use with changing the default date format is as follows:

ALTER SESSION SET NLS_DATE_FORMAT = date_format;

The date_format can include the following codes:

YY A 2 digit year such as 98.


YYYY A 4 digit year such as 1998.
NM A month number.
MONTH The full name of the month.
MON The abbreviated month (Jan, Feb, Mar).
DDD The day of the year. For use is Julian dates.
DD The day of the month.
D The day of the week.
DAY The name of the day.

For example, to change the default date to include a full four digit year, issue the following ALTER SESSION
statement:

ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MON-YYYY'

From this point, all INSERT, UPDATE and DELETE statements must format the date accordingly. Also, any
SELECT statements will return the date formatted accordingly.
7
Compiled by Manas Ghosh
Note that this change only remains in effect for the current session. Logging out of SQL*Plus and logging
back in (or re-connecting to the Oracle database using the connect command) will reset the date format back
to its default.

The RR Date Format Element

The RR date format element is similar to the YY date format element, but it provides additional flexibility for
storing date values in other centuries. The RR date format element allows you to store twenty-first century
dates in the twentieth century by specifying only the last two digits of the year. It will also allow you to store
twentieth century dates in the twenty-first century in the same way if necessary.

If you use the TO_DATE function with the YY date format element, the date value returned is always in the
current century. If you use the RR date format element instead, the century of the return value varies
according to the specified two-digit year and the last two digits of the current year. The following table
summarizes the behavior of the RR date format element.

If the specified two-digit year is


0 - 49 50 - 99
If the last two digits of the 0-49 The return date is in the current The return date is in the century
current year are: century. before the current one.
50-99 The return date is in the century The return date is in the current
after the current one. century.
The RR Date Element Format

The following example demonstrates the behavior of the RR date format element.

Illustration:

Assume these queries are issued between 1950 and 1999:

SELECT TO_CHAR(TO_DATE('27-OCT-95', 'DD-MON-RR'),'YYYY') "4-digit year" FROM


DUAL;

4-digit year
------------
1995

SELECT TO_CHAR(TO_DATE('27-OCT-17', 'DD-MON-RR'),'YYYY') "4-digit year" FROM


DUAL ;

4-digit year
------------
2017

Assume these queries are issued between 2000 and 2049:

SELECT TO_CHAR(TO_DATE('27-OCT-95', 'DD-MON-RR'),'YYYY') "4-digit year"


FROM DUAL

4-digit year
------------
1995

SELECT TO_CHAR(TO_DATE('27-OCT-17','DD-MON-RR'),'YYYY') "4-digit year"


FROM DUAL;

8
Compiled by Manas Ghosh
4-digit year
------------
2017

Note that the queries return the same values regardless of whether they are issued before or after the year
2000. The RR date format element allows you to write SQL statements that will return the same values after
the turn of the century.

 S o me a d d i t i o n a l i m p o r t a n t f u n c t i o n s a r e :

DECODE (s, search1, result1, Compares s with search1, search2, etc. and returns the
search2, result2) corresponding result when there is a match.
NVL (s, expression) If s is NULL, return expression. If s is not null, then return s.
USER Returns the username of the current user.
For example: SELECT USER FROM DUAL;

Suppose, in EMP table, there is a column SEX of type VARCHAR2(1). It contains either ’ M’ for male
employee or ‘F’ for female employee. Now it is needed to return "MALE" if the value is "M" ; "FEMALE" if the
value is "F" ; "UNKNOWN" if the field is neither M nor F. The query to do this will be

SELECT ecode, ename,


DECODE(sex,’M’,’MALE’,’F’,’FEMALE’,’UNKNOWN’)
FROM emp;
The following example illustrates the NVL() function. There are some tuples for which the values for the
‘comm’ column are NULL.

SELECT ename, NVL(TO_CHAR(COMM),'NOT APPLICABLE') "COMMISSION"


FROM emp
WHERE deptno = 30

ENAME COMMISSION
--------- -----------
BAKER 300
MAY 500
JOLLEY 1400
KOEHL NOT APPLICABLE
LAZARRO 0
FREER NOT APPLICABLE

How to Convert Numbers to Characters?

You can convert numeric values to characters by using the TO_CHAR() function as shown in the
following examples:

SELECT TO_CHAR(4123.4570) FROM DUAL


123.457

SELECT TO_CHAR(4123.457, '$9,999,999.99') FROM DUAL


$4,123.46

SELECT TO_CHAR(-4123.457, '9999999.99EEEE') FROM DUAL


-4.12E+03

9
Compiled by Manas Ghosh
How to Convert Characters to Numbers?

You can convert characters to numbers by using the TO_NUMBER() function as shown in the
following examples:

SELECT TO_NUMBER('4123.4570') FROM DUAL


4123.457

SELECT TO_NUMBER(' $4,123.46','$9,999,999.99') FROM DUAL


4123.46

SELECT TO_NUMBER(' -4.12E+03') FROM DUAL


-4120

How to Convert Dates to Characters?

You can convert dates to characters using the TO_CHAR() function as shown in the following
examples:

SELECT TO_CHAR(SYSDATE, 'DD-MON-YYYY') FROM DUAL;


-- SYSDATE returns the current date

07-MAY-2006

SELECT TO_CHAR(SYSDATE, 'YYYY/MM/DD') FROM DUAL;

2006/05/07

SELECT TO_CHAR(SYSDATE, 'MONTH DD, YYYY') FROM DUAL;

MAY 07, 2006

SELECT TO_CHAR(SYSDATE, 'fmMONTH DD, YYYY') FROM DUAL;

May 7, 2006

SELECT TO_CHAR(SYSDATE, 'fmDAY, MONTH DD, YYYY') FROM DUAL;

SUNDAY, MAY 7, 2006

How To Convert Characters to Dates?

You can convert dates to characters using the TO_DATE() function as shown in the following
examples:

SELECT TO_DATE('07-MAY-2006', 'DD-MON-YYYY') FROM DUAL;

07-MAY-06

SELECT TO_DATE('2006/05/07 ', 'YYYY/MM/DD') FROM DUAL;

07-MAY-06

SELECT TO_DATE('MAY 07, 2006', 'MONTH DD, YYYY') FROM DUAL;

07-MAY-06

10
Compiled by Manas Ghosh
SELECT TO_DATE('May 7, 2006', 'fmMONTH DD, YYYY') FROM DUAL;

07-MAY-06

SELECT TO_DATE('SUNDAY, MAY 7, 2006', 'fmDAY, MONTH DD, YYYY') FROM


DUAL;
07-MAY-06

How to Convert Times to Characters?

You can convert dates to characters using the TO_CHAR() function as shown in the following
examples:

SELECT TO_CHAR(SYSDATE, 'HH:MI:SS') FROM DUAL;

04:49:49

SELECT TO_CHAR(SYSDATE, 'HH24:MI:SS.FF') FROM DUAL;


-- Error: SYSDATE has no fractional seconds

SELECT TO_CHAR(SYSTIMESTAMP, 'HH24:MI:SS.FF9') FROM DUAL;

16:52:57.847000000

SELECT TO_CHAR(SYSDATE, 'SSSSS') FROM DUAL;


-- Seconds past midnight

69520

11
Compiled by Manas Ghosh

You might also like