PL/SQL - ALTER FUNCTION

PL/SQL - ALTER FUNCTION
1. How to ALTER FUNCTION?
 Alter function is used to recompile a stand-alone stored function.
SYNTAX: ALTER FUNCTION [schema.] function COMPILE 
 
Schema 
    is the schema containing the function.  If you omit schema, Oracle 
    assumes the function is in your own schema. 
 
Function 
    is the name of the function to be recompiled. 
 
COMPILE 
Causes  Oracle to recompile the function.  The COMPILE keyword is  required. 
 
PREREQUISITES: 
 The function must be in your own schema or you must have ALTER ANY   PROCEDURE system privilege. 
 
    If you are using Trusted Oracle in DBMS MAC mode, your DBMS label  must match the function's creation label or you must satisfy one of   these criteria: 
 
* If the function's creation label is higher than your DBMS label,  you must have READUP and WRITEUP system privileges. 
 
 * If the function's creation label is lower than your DBMS label,  you must have WRITEDOWN system privilege. 
 

 * If the function's creation label and your DBMS label are   non-comparable, you must have READUP, WRITEUP, and WRITEDOWN system   privileges. 

PL/SQL - restrictions on calling Functions from SQL Expressions

PL/SQL - restrictions on calling Functions from SQL Expressions
1. What are the restrictions on calling Functions from SQL Expressions?
To be callable from SQL expressions, a user-defined PL/SQL function must meet certain requirements.

• Parameters to a PL/SQL function called from a SQL statement must use positional notation.
    Named notation is not supported.

• Stored PL/SQL functions cannot be called from the CHECK constraint clause of a CREATE or
ALTER TABLE command or be used to specify a default value for a column.

• User must have the EXECUTE privilege on the function to call it from a SQL statement.

• The functions must return data types that are valid SQL data types. They cannot be PL/SQL specific
data types such as BOOLEAN, RECORD, or TABLE. The same restriction applies to parameters of the function.

Note: Only stored functions are callable from SQL statements. Stored procedures cannot be called.
The ability to use a user-defined PL/SQL function in a SQL expression is available with PL/SQL 2.1
and later. Tools using earlier versions of PL/SQL do not support this functionality. Prior to Oracle9i,
user-defined functions can be only single-row functions. Starting with Oracle9i, user-defined functions
can also be defined as aggregate functions.

Note: Functions that  are callable from SQL expressions cannot contain OUT and IN OUT parameters.
Other functions can contain parameters with these modes, but it is not recommended.

PL/SQL - invoke the Functions in SQL Expressions

PL/SQL -  invoke the Functions in SQL Expressions
1.  How to invoke the Functions in SQL Expressions?
We invoke the SQL functions when activates are   too complex, too awkward, or unavailable with SQL.
By invoking functions we can increase efficiency when used in the WHERE clause to filter data, as opposed to filtering the data in the application and also we can manipulate character strings.

Advantages
• Permits calculations that are too complex, awkward, or unavailable with SQL.
• Increases data independence by processing complex data analysis within the Oracle server,
rather than by retrieving the data into an application
• Increases efficiency of queries by performing functions in the query rather than in the
application
• Manipulates new types of data (for example, latitude and longitude) by encoding character
    strings and using functions to operate on the strings.


CREATE OR REPLACE FUNCTION tax(p_value IN NUMBER)
RETURN NUMBER IS
BEGIN
RETURN (p_value * 0.08);
END tax;
/

SELECT employee_id, last_name, salary, tax(salary)
FROM employees WHERE department_id = 100;

PL/SQL - Forward Declarations

PL/SQL - Forward Declarations
1 . What are the Forward Declarations?

PL/SQL is rather fussy about its requirement that you declare a variable, cursor, or module before you use it in your code. Otherwise, how can PL/SQL be sure that the way you are using the object is appropriate? Since modules can call other modules, however, you can encounter situations where it is completely impossible to define all modules before any references to those modules are made. What if program A calls program B and program B calls program A? PL/SQL supports mutual recursion, where two or more programs directly or indirectly call each other.
If you do find yourself committed to mutual recursion, you will be very glad to hear that PL/SQL supports the forward declaration of local modules, which declares a module in advance of the actual definition of that program. This declaration makes that program available to be called by other programs even before the program definition.
Remember that both procedures and functions have a header and a body. A forward declaration consists simply of the program header, followed by a semicolon (;). This construction is called the module header. This header, which must include the parameter list (and RETURN clause if a function) is all the information PL/SQL needs about a module in order to declare it and resolve any references to that module; a module should, after all, be a little black box.
The following example will illustrate the technique. I define two mutually recursive functions within a procedure. Consequently I have to declare just the header of my second function, total_cost, before the full declaration of net_profit:

PROCEDURE perform_calcs (year_in IN INTEGER)
IS
   /* Header only for total_cost function. */
   FUNCTION total_cost (. . .)  RETURN NUMBER;

   /* The net_profit function uses total_cost. */
   FUNCTION net_profit (. . .) RETURN NUMBER
   IS
   BEGIN
      RETURN tot_sales (. . .) - total_cost (. . .);
   END;



   /* The total_cost function uses net_profit. */
   FUNCTION total_cost (. . .)  RETURN NUMBER
   IS
   BEGIN
      IF net_profit (. . .) < 0
      THEN
         RETURN 0;
      ELSE
         RETURN . . .;
      END IF;
   END;
BEGIN
   . . .
END;


Here are some rules to remember concerning forward declarations:
You cannot make forward declarations of a variable or cursor. This technique works only with modules (procedures and functions).
The definition for a forwardly-declared program must be contained in the declaration section of the same PL/SQL block (anonymous block, procedure, function, or package) in which you code the forward declaration.
In some situations, you absolutely require forward declarations; in most situations, they just help make your code more readable and presentable. As with every other advanced or unusual feature of the PL/SQL language, use forward declarations only when you really need the functionality. Otherwise, the declarations simply add to the clutter of your program, which is the last thing you want.


PL/SQL - Module Overloading

PL/SQL - Module Overloading

Module Overloading

Two or more modules can, under certain conditions, have the same name with different parameter lists. Such modules are said to be overloaded. The code in these overloaded programs can be very similar or can be completely different. Here is an example of two overloaded modules defined in the declaration section of an anonymous block (both are local modules):

DECLARE
   /* First version takes a DATE parameter. */
   FUNCTION value_ok (date_in IN DATE) RETURN BOOLEAN
   IS
   BEGIN
      RETURN date_in <= SYSDATE;
   END;

   /* Second version takes a NUMBER parameter. */
   FUNCTION value_ok (number_in IN NUMBER) RETURN BOOLEAN
   IS
   BEGIN
      RETURN number_in > 0;
   END;

BEGIN
When the PL/SQL run-time engine encounters the following statement:
IF value_ok (SYSDATE) THEN ...
the compile compares the actual parameter against the different parameter lists for the overloaded modules. It then executes the code in the body of the program with the matching header.

1. What are the Benefits of Overloading in Function?

Overloading can greatly simplify your life and the lives of other developers. This technique consolidates the call interfaces for many similar programs into a single module name. This process transfers the burden of knowledge from the developer to the software. You do not have to try to remember, for instance, the six different names for programs adding values (dates, strings, Booleans, numbers, etc.) to various PL/SQL tables. Instead, you simply tell the compiler that you want to add and pass it the value you want added. PL/SQL and your overloaded programs figure out what you want to do and they do it for you.

When you build overloaded modules, you spend more time in design and implementation than you might with separate, standalone modules. This additional up-front time will be repaid handsomely down the line. You and others will find that it is easier and more efficient to use your programs.

Where to Overload Modules
  • There are only two places in PL/SQL programs where you can overload modules:
  • Inside the declaration section of a PL/SQL block
  • Inside a package

2. What are the restrictions on Overloading?
There are several restrictions on how you can overload programs. When the PL/SQL engine compiles and runs your program, it has to be able to distinguish between the different overloaded versions of a program; after all, it can't run two different modules at the same time. So when you compile your code, PL/SQL will reject any improperly overloaded modules. It cannot distinguish between the modules by their name, because by definition that is the same in all overloaded programs. Instead, PL/SQL uses the parameter lists of these sibling programs to determine which one to execute. As a result, the following restrictions apply to overloaded programs.

The datatype family of at least one of the parameters of overloaded programs must differ. INTEGER, REAL, DECIMAL, FLOAT, etc., are NUMBER subtypes. CHAR, VARCHAR2, and LONG are character subtypes. If the parameters differ only by datatype within the supertype or family of datatypes, PL/SQL does not have enough information with which to determine the appropriate program to execute. As a result, the following programs cannot be overloaded:

PL/SQL - Local Modules

PL/SQL - Local Modules

1. What are the Local Modules?
A local module is a procedure or function that is defined in the declaration section of a PL/SQL block (anonymous or named). This module is considered local because it is only defined within the parent PL/SQL block. It cannot be called by any other PL/SQL blocks defined outside of that enclosing block.
The syntax for defining the procedure or function is exactly the same as that used for creating standalone modules.
The following anonymous block, for example, declares a local procedure:

DECLARE
   PROCEDURE show_date (date_in IN DATE) IS
   BEGIN
      DBMS_OUTPUT.PUT_LINE (TO_CHAR (date_in, 'Month DD, YYYY');
   END;
BEGIN
   ...
END;

Local modules must be located after all of the other declaration statements in the declaration section. You must declare your variables, cursors, exceptions, types, records, tables, and so on, before you type in the first PROCEDURE or FUNCTION keyword.
You can define both procedures and functions in the declaration section of any kind of PL/SQL block, be it anonymous, procedure, or function. You may not, however, define anonymous blocks (how would you call them?) or packages (maybe in a future release) in a declaration section.
The rest of this section explores the benefits of local modules and offers a number of examples.



 2. What are the Benefits of Local Modularization?

There are two central reasons to create local modules:
Reduce the size of the module by stripping it of repetitive code. This is the most common motivation to create a local module. You can see the impact by the next example. The code reduction leads to higher code quality because you have fewer lines to test and fewer potential bugs. It takes less effort to maintain the code, because there is less to maintain. When you do have to make a change, you make it in one place in the local module and the effects are felt immediately throughout the parent module.
Improve the readability of your code. Even if you do not repeat sections of code within a module, you still may want to pull out a set of related statements and package them into a local module to make it easier to follow the logic of the main body of the parent module.

Reducing Code Volume
Let's take a look at an example. The calc_percentages procedure takes numeric values from the sales package (sales_pkg), calculates the percentage of each sales amount against the total sales provided as a parameter, and then formats the number for display in a report or form. The example you see here has only three calculations, but I extracted it from a production application that actually performed 23 of these computations!

PROCEDURE calc_percentages (tot_sales_in IN NUMBER)
IS
BEGIN
   :profile.food_sales_stg :=
      TO_CHAR ((sales_pkg.food_sales / tot_sales_in ) * 100,
               '$999,999');
   :profile.service_sales_stg :=
      TO_CHAR ((sales_pkg.service_sales / tot_sales_in ) * 100,
               '$999,999');
   :profile.toy_sales_stg :=
      TO_CHAR ((sales_pkg.toy_sales / tot_sales_in ) * 100,
               '$999,999');
END;

This code took a long time (relatively speaking) to write, is larger in code size than necessary, and is maintenance-intensive. What if I need to change the format to which I convert the numbers? What if the calculation of the percentage changes? I have to change each of the individual calculations.
With local modules, I can concentrate all the common, repeated code into a single function, which is then called repeatedly in calc_percentages. The local module version of this procedure is shown below:

PROCEDURE calc_percentages (tot_sales_in IN NUMBER)
IS
   /* Define a function right inside the procedure! */
   FUNCTION char_format (val_in IN NUMBER) RETURN VARCHAR2
   IS
   BEGIN
      RETURN TO_CHAR ((val_in/tot_sales_in ) * 100, '$999,999');
   END;
BEGIN
   :profile.food_sales_stg := char_format (sales_pkg.food_sales);
   :profile.service_sales_stg := char_format (sales_pkg.service_sales);
   :profile.toy_sales_stg := char_format (sales_pkg.toy_sales);
END;


All the complexities of the calculation, from the division by tot_sales_in to the multiplication by 100 to the formatting with TO_CHAR, have been transferred to the function, pct_stg. This function is defined in the declaration section of the procedure. By calling this function from within the body of calc_percentages, the executable statements of the procedure are much more readable and maintainable. Now, if the formula for the calculation changes in any way, I make the change just once in the function and it takes effect in all the assignments.

PL/SQL - Object Oriented


PL/SQL allows defining an object type, which helps in designing object-oriented database in Oracle. An object type allows you to crate composite types. Using objects allow you implementing real world objects with specific structure of data and methods for operating it. Objects have attributes and methods. Attributes are properties of an object and are used for storing an object's state; and methods are used for modeling its behaviors.
Objects are created using the CREATE [OR REPLACE] TYPE statement. Below is an example to create a simple address object consisting of few attributes:
CREATE OR REPLACE TYPE address AS OBJECT
(house_no varchar2(10),
 street varchar2(30),
 city varchar2(20),
 state varchar2(10),
 pincode varchar2(10)
);
/
When the above code is executed at SQL prompt, it produces the following result:
Type created.
Let's create one more object customer where we will wrap attributes and methods together to have object oriented feeling:
CREATE OR REPLACE TYPE customer AS OBJECT
(code number(5),
 name varchar2(30),
 contact_no varchar2(12),
 addr address,
 member procedure display
);
/
When the above code is executed at SQL prompt, it produces the following result:
Type created.

Instantiating an Object

Defining an object type provides a blueprint for the object. To use this object, you need to create instances of this object. You can access the attributes and methods of the object using the instance name and the access operator (.) as follows:
DECLARE
   residence address;
BEGIN
   residence := address('103A', 'M.G.Road', 'Jaipur', 'Rajasthan','201301');
   dbms_output.put_line('House No: '|| residence.house_no);
   dbms_output.put_line('Street: '|| residence.street);
   dbms_output.put_line('City: '|| residence.city);
   dbms_output.put_line('State: '|| residence.state);
   dbms_output.put_line('Pincode: '|| residence.pincode);
END;
/
When the above code is executed at SQL prompt, it produces the following result:
House No: 103A
Street: M.G.Road
City: Jaipur
State: Rajasthan
Pincode: 201301

PL/SQL procedure successfully completed.

Member Methods

Member methods are used for manipulating the attributes of the object. You provide the declaration of a member method while declaring the object type. The object body defines the code for the member methods. The object body is created using the CREATE TYPE BODY statement.
Constructors are functions that return a new object as its value. Every object has a system defined constructor method. The name of the constructor is same as the object type. For example:
residence := address('103A', 'M.G.Road', 'Jaipur', 'Rajasthan','201301');
The comparison methods are used for comparing objects. There are two ways to compare objects:
  • Map method: The Map method is a function implemented in such a way that its value depends upon the value of the attributes. For example, for a customer object, if the customer code is same for two customers, both customers could be the same and one. So the relationship between these two objects would depend upon the value of code.
  • Order method: The Order methods implement some internal logic for comparing two objects. For example, for a rectangle object, a rectangle is bigger than another rectangle if both its sides are bigger.

Using Map method

Let us try to understand above concepts using the following rectangle object:
CREATE OR REPLACE TYPE rectangle AS OBJECT
(length number,
 width number,
 member function enlarge( inc number) return rectangle,
 member procedure display,
 map member function measure return number
);
/
When the above code is executed at SQL prompt, it produces the following result:
Type created.
Creating the type body:
CREATE OR REPLACE TYPE BODY rectangle AS
   MEMBER FUNCTION enlarge(inc number) return rectangle IS
   BEGIN
      return rectangle(self.length + inc, self.width + inc);
   END enlarge;

   MEMBER PROCEDURE display IS
   BEGIN
      dbms_output.put_line('Length: '|| length);
      dbms_output.put_line('Width: '|| width);
   END display;

   MAP MEMBER FUNCTION measure return number IS
   BEGIN
      return (sqrt(length*length + width*width));
   END measure;
END;
/
When the above code is executed at SQL prompt, it produces the following result:
Type body created.
Now using the rectangle object and its member functions:
DECLARE
   r1 rectangle;
   r2 rectangle;
   r3 rectangle;
   inc_factor number := 5;
BEGIN
   r1 := rectangle(3, 4);
   r2 := rectangle(5, 7);
   r3 := r1.enlarge(inc_factor);
   r3.display;

   IF (r1 > r2) THEN -- calling measure function
      r1.display;
   ELSE
      r2.display;
   END IF;
END;
/
When the above code is executed at SQL prompt, it produces the following result:
Length: 8
Width: 9
Length: 5
Width: 7

PL/SQL procedure successfully completed.

Using Order method

Now, the same effect could be achieved using an order method. Let us recreate the rectangle object using an order method:
CREATE OR REPLACE TYPE rectangle AS OBJECT
(length number,
 width number,
 member procedure display,
 order member function measure(r rectangle) return number
);
/
When the above code is executed at SQL prompt, it produces the following result:
Type created.
Creating the type body:
CREATE OR REPLACE TYPE BODY rectangle AS
   MEMBER PROCEDURE display IS
   BEGIN
      dbms_output.put_line('Length: '|| length);
      dbms_output.put_line('Width: '|| width);
   END display;

   ORDER MEMBER FUNCTION measure(r rectangle) return number IS
   BEGIN
      IF(sqrt(self.length*self.length + self.width*self.width)> sqrt(r.length*r.length + r.width*r.width)) then
         return(1);
      ELSE
         return(-1);
      END IF;
   END measure;
END;
/
When the above code is executed at SQL prompt, it produces the following result:
Type body created.
Using the rectangle object and its member functions:
DECLARE
   r1 rectangle;
   r2 rectangle;
BEGIN
   r1 := rectangle(23, 44);
   r2 := rectangle(15, 17);
   r1.display;
   r2.display;
   IF (r1 > r2) THEN -- calling measure function
      r1.display;
   ELSE
      r2.display;
   END IF;
END;
/
When the above code is executed at SQL prompt, it produces the following result:
Length: 23
Width: 44
Length: 15
Width: 17
Length: 23
Width: 44

PL/SQL procedure successfully completed.

Inheritance for PL/SQL Objects:

PL/SQL allows creating object from existing base objects. To implement inheritance, the base objects should be declared as NOT FINAL. The default is FINAL.
The following programs illustrate inheritance in PL/SQL Objects. Let us create another object named TableTop, which is inheriting from the Rectangle object. Creating the base rectangle object:
CREATE OR REPLACE TYPE rectangle AS OBJECT
(length number,
 width number,
 member function enlarge( inc number) return rectangle,
 NOT FINAL member procedure display) NOT FINAL
/
When the above code is executed at SQL prompt, it produces the following result:
Type created.
Creating the base type body:
CREATE OR REPLACE TYPE BODY rectangle AS
   MEMBER FUNCTION enlarge(inc number) return rectangle IS
   BEGIN
      return rectangle(self.length + inc, self.width + inc);
   END enlarge;

   MEMBER PROCEDURE display IS
   BEGIN
      dbms_output.put_line('Length: '|| length);
      dbms_output.put_line('Width: '|| width);
   END display;
END;
/
When the above code is executed at SQL prompt, it produces the following result:
Type body created.
Creating the child object tabletop:
CREATE OR REPLACE TYPE tabletop UNDER rectangle
(  
   material varchar2(20);
   OVERRIDING member procedure display
)
/
When the above code is executed at SQL prompt, it produces the following result:
Type created.
Creating the type body for the child object tabletop:
CREATE OR REPLACE TYPE BODY tabletop AS
OVERRIDING MEMBER PROCEDURE display IS
BEGIN
   dbms_output.put_line('Length: '|| length);
   dbms_output.put_line('Width: '|| width);
   dbms_output.put_line('Material: '|| material);
END display;
/
When the above code is executed at SQL prompt, it produces the following result:
Type body created.
Using the tabletop object and its member functions:
DECLARE
   t1 tabletop;
   t2 tabletop;
BEGIN
   t1:= tabletop(20, 10, 'Wood');
   t2 := tabletop(50, 30, 'Steel');
   t1.display;
   t2.display;
END;
/
When the above code is executed at SQL prompt, it produces the following result:
Length: 20
Width: 10
Material: Wood
Length: 50
Width: 30
Material: Steel

PL/SQL procedure successfully completed.

Abstract Objects in PL/SQL

The NOT INSTANTIABLE clause allows you to declare an abstract object. You cannot use an abstract object as it is; you will have to create a subtype or child type of such objects to use its functionalities.
For example,
CREATE OR REPLACE TYPE rectangle AS OBJECT
(length number,
 width number,
 NOT INSTANTIABLE NOT FINAL MEMBER PROCEDURE display) 
 NOT INSTANTIABLE NOT FINAL
/
When the above code is executed at SQL prompt, it produces the following result:
Type created.

Complete Tutorial

PL/SQL - DBMS Output


The DBMS_OUTPUT is a built-in package that enables you to display output, display debugging information, and send messages from PL/SQL blocks, subprograms, packages, and triggers. We have already used this package all throughout our tutorial.
Let us look at a small code snippet that would display all the user tables in the database. Try it in your database to list down all the table names:
BEGIN
   dbms_output.put_line  (user || ' Tables in the database:');
   FOR t IN (SELECT table_name FROM user_tables)
   LOOP
      dbms_output.put_line(t.table_name);
   END LOOP;
END;
/

DBMS_OUTPUT Subprograms

The DBMS_OUTPUT package has the following subprograms:
S.NSubprogram & Purpose
1DBMS_OUTPUT.DISABLE;
Disables message output
2DBMS_OUTPUT.ENABLE(buffer_size IN INTEGER DEFAULT 20000);
Enables message output. A NULL value of buffer_size represents unlimited buffer size.
3DBMS_OUTPUT.GET_LINE (line OUT VARCHAR2, status OUT INTEGER);
Retrieves a single line of buffered information.
4DBMS_OUTPUT.GET_LINES (lines OUT CHARARR, numlines IN OUT INTEGER);
Retrieves an array of lines from the buffer.
5DBMS_OUTPUT.NEW_LINE;
Puts an end-of-line marker
6DBMS_OUTPUT.PUT(item IN VARCHAR2);
Places a partial line in the buffer.
7DBMS_OUTPUT.PUT_LINE(item IN VARCHAR2);
Places a line in the buffer.

Example:

DECLARE
   lines dbms_output.chararr;
   num_lines number;
BEGIN
   -- enable the buffer with default size 20000
   dbms_output.enable;
  
   dbms_output.put_line('Hello Reader!');
   dbms_output.put_line('Hope you have enjoyed the tutorials!');
   dbms_output.put_line('Have a great time exploring pl/sql!');
 
   num_lines := 3;
 
   dbms_output.get_lines(lines, num_lines);
 
   FOR i IN 1..num_lines LOOP
      dbms_output.put_line(lines(i));
   END LOOP;
END;
/
When the above code is executed at SQL prompt, it produces the following result:
Hello Reader!
Hope you have enjoyed the tutorials!
Have a great time exploring pl/sql!

PL/SQL procedure successfully completed.

Complete Tutorial

PL/SQL - Date & Time


PL/SQL provides two classes of date and time related data types:
  • Datetime data types
  • Interval data types
The Datetime data types are:
  • DATE
  • TIMESTAMP
  • TIMESTAMP WITH TIME ZONE
  • TIMESTAMP WITH LOCAL TIME ZONE
The Interval data types are:
  • INTERVAL YEAR TO MONTH
  • INTERVAL DAY TO SECOND

Field Values for Datetime and Interval Data Types

Both datetime and interval data types consist of fields. The values of these fields determine the value of the datatype. The following table lists the fields and their possible values for datetimes and intervals.
Field NameValid Datetime ValuesValid Interval Values
YEAR-4712 to 9999 (excluding year 0)Any nonzero integer
MONTH01 to 120 to 11
DAY01 to 31 (limited by the values of MONTH and YEAR, according to the rules of the calendar for the locale)Any nonzero integer
HOUR00 to 230 to 23
MINUTE00 to 590 to 59
SECOND00 to 59.9(n), where 9(n) is the precision of time fractional seconds
The 9(n) portion is not applicable for DATE.
0 to 59.9(n), where 9(n) is the precision of interval fractional seconds
TIMEZONE_HOUR-12 to 14 (range accommodates daylight savings time changes)
Not applicable for DATE or TIMESTAMP.
Not applicable
TIMEZONE_MINUTE00 to 59
Not applicable for DATE or TIMESTAMP.
Not applicable
TIMEZONE_REGIONNot applicable for DATE or TIMESTAMP.Not applicable
TIMEZONE_ABBRNot applicable for DATE or TIMESTAMP.Not applicable

The Datetime Data Types and Functions

Following are the Datetime data types:
  • DATE - it stores date and time information in both character and number datatypes. It is made of information on century, year, month, date, hour, minute, and second. It is specified as:
  • TIMESTAMP - it is an extension of the DATE datatype. It stores the year, month, and day of the DATE datatype, along with hour, minute, and second values. It is useful for storing precise time values.
  • TIMESTAMP WITH TIME ZONE - it is a variant of TIMESTAMP that includes a time zone region name or a time zone offset in its value. The time zone offset is the difference (in hours and minutes) between local time and UTC. This datatype is useful for collecting and evaluating date information across geographic regions.
  • TIMESTAMP WITH LOCAL TIME ZONE - it is another variant of TIMESTAMP that includes a time zone offset in its value.
Following table provides the Datetime functions (where, x has datetime value):
S.NFunction Name & Description
1ADD_MONTHS(x, y);
Adds y months to x.
2LAST_DAY(x);
Returns the last day of the month.
3MONTHS_BETWEEN(x, y);
Returns the number of months between x and y.
4NEXT_DAY(x, day);
Returns the datetime of the next day after x.
5NEW_TIME;
Returns the time/day value from a time zone specified by the user.
6ROUND(x [, unit]);
Rounds x;
7SYSDATE();
Returns the current datetime.
8TRUNC(x [, unit]);
Truncates x.
Timestamp functions (where, x has a timestamp value):
S.NFunction Name & Description
1CURRENT_TIMESTAMP();
Returns a TIMESTAMP WITH TIME ZONE containing the current session time along with the session time zone.
2EXTRACT({ YEAR | MONTH | DAY | HOUR | MINUTE | SECOND } | { TIMEZONE_HOUR | TIMEZONE_MINUTE } | { TIMEZONE_REGION | } TIMEZONE_ABBR ) FROM x)
Extracts and returns a year, month, day, hour, minute, second, or time zone from x;
3FROM_TZ(x, time_zone);
Converts the TIMESTAMP x and time zone specified by time_zone to a TIMESTAMP WITH TIMEZONE.
4LOCALTIMESTAMP();
Returns a TIMESTAMP containing the local time in the session time zone.
5SYSTIMESTAMP();
Returns a TIMESTAMP WITH TIME ZONE containing the current database time along with the database time zone.
6SYS_EXTRACT_UTC(x);
Converts the TIMESTAMP WITH TIMEZONE x to a TIMESTAMP containing the date and time in UTC.
7TO_TIMESTAMP(x, [format]);
Converts the string x to a TIMESTAMP.
8TO_TIMESTAMP_TZ(x, [format]);
Converts the string x to a TIMESTAMP WITH TIMEZONE.

Examples:

The following code snippets illustrate the use of the above functions:
SELECT SYSDATE FROM DUAL;
Output:
08/31/2012 5:25:34 PM
SELECT TO_CHAR(CURRENT_DATE, 'DD-MM-YYYY HH:MI:SS') FROM DUAL;
Output:
31-08-2012 05:26:14
SELECT ADD_MONTHS(SYSDATE, 5) FROM DUAL;
Output:
01/31/2013 5:26:31 PM
SELECT LOCALTIMESTAMP FROM DUAL;
Output:
8/31/2012 5:26:55.347000 PM

The Interval Data Types and Functions

Following are the Interval data types:
  • INTERVAL YEAR TO MONTH - it stores a period of time using the YEAR and MONTH datetime fields.
  • INTERVAL DAY TO SECOND - it stores a period of time in terms of days, hours, minutes, and seconds.
Interval functions:
S.NFunction Name & Description
1NUMTODSINTERVAL(x, interval_unit);
Converts the number x to an INTERVAL DAY TO SECOND.
2NUMTOYMINTERVAL(x, interval_unit);
Converts the number x to an INTERVAL YEAR TO MONTH.
3TO_DSINTERVAL(x);
Converts the string x to an INTERVAL DAY TO SECOND.
4TO_YMINTERVAL(x);
Converts the string x to an INTERVAL YEAR TO MONTH.

Complete Tutorial