Friday, 6 July 2012


In and around Oracle Application, as a developer you need to play with Dates while writing your code. Playing with dates is fun, although sometimes we faced some challenging tasks. Therefore it is always helpful to go through this feature of Oracle in detail. I did the same and here is what I have found.
Oracle database stores dates in an internal numeric format, representing the century, year, month, day, hours, minutes, and seconds. The default display and input format for any date is DD-MON-YY. Valid Oracle dates are between January 1, 4712 B.C. and December 31, 9999 A.D.
Unlike other datatypes, DATE datatypes are bit complex. However, Oracle Database and PL/SQL provide a set of true date and time datatypes that store both date and time information in a standard internal format, and they also have an extensive set of built-in functions for manipulating the date and time.
Get the current date and time:
Often it is required to retrieve the current date and time in our code and use them. Many developers go with SYSDATE function, but Oracle Database now offers several other functions as well.
02--27-FEB-12 (You will get the DATE from Oracle Database Server)
04--27-FEB-12 (You will get the Current DATE from Oracle Session Time Zone)
06--27-FEB-12 AM (You will get the TIMESTAMP from Oracle Session Time Zone)
08--27-FEB-12 AM -06:00 (You will get the TIMESTAMP WITH TIME ZONE from Oracle Database Server)
10--27-FEB-12 AM AMERICA/CHICAGO (You will get the TIMESTAMP WITH TIME ZONE from Oracle Session Time Zone)
DATE Format:
When a DATE value is displayed, Oracle must first convert that value from the special internal format to a printable string. The conversion is done by a function TO_CHAR, according to a DATE format. Oracle’s default format for DATE is “DD-MON-YY”. Whenever a DATE value is displayed, Oracle will call TO_CHAR automatically with the default DATE format. However, you may override the default behavior by calling TO_CHAR explicitly with your own DATE format.
  • The format model must be enclosed in single quotation marks and is case sensitive.
  • The format model can include any valid date format element. Be sure to separate the date value from the format model by a comma.
  • The names of days and months in the output are automatically padded with blanks.
  • To remove padded blanks or to suppress leading zeros, use the fill mode fm element.
YEAR Year, spelled out
YYYY 4-digit year
Last 3, 2, or 1 digit(s) of year.
Last 3, 2, or 1 digit(s) of ISO year.
IYYY 4-digit year based on the ISO standard
Q Quarter of year (1, 2, 3, 4; JAN-MAR = 1).
MM Month (01-12; JAN = 01).
MON Abbreviated name of month.
MONTH Name of month, padded with blanks to length of 9 characters.
RM Roman numeral month (I-XII; JAN = I).
WW Week of year (1-53) where week 1 starts on the first day of the year and continues to the seventh day of the year.
W Week of month (1-5) where week 1 starts on the first day of the month and ends on the seventh.
IW Week of year (1-52 or 1-53) based on the ISO standard.
D Day of week (1-7).
DAY Name of day.
DD Day of month (1-31).
DDD Day of year (1-366).
DY Abbreviated name of day.
J Julian day; the number of days since January 1, 4712 BC.
HH Hour of day (1-12).
HH12 Hour of day (1-12).
HH24 Hour of day (0-23).
MI Minute (0-59).
SS Second (0-59).
SSSSS Seconds past midnight (0-86399).
FF Fractional seconds.
01SELECT TO_CHAR(SYSDATE, 'yyyy/mm/dd') FROM DUAL; -- Returns 2012/02/27
02SELECT TO_CHAR(SYSDATE, 'Month DD, YYYY') FROM DUAL; -- Returns February  27, 2012
03SELECT TO_CHAR(SYSDATE, 'FMMonth DD, YYYY') FROM DUAL; -- Returns February 27, 2012
06SELECT TO_CHAR(SYSDATE, 'FMMonth DD, YYYY') FROM DUAL; -- Returns February 27, 2012
07SELECT TO_CHAR(SYSDATE, 'FMDay, DDth Month YYYY') FROM DUAL; -- Returns Monday, 27TH February 2012
08SELECT TO_CHAR(SYSDATE, 'YYYY-MM-DD HH24:MI:SS') FROM DUAL; -- Returns 2012-02-27 02:05:59
09SELECT TO_CHAR(SYSDATE, 'FMDdspth "of" Month YYYY FMHH:MI:SS AM') FROM DUAL; -- Returns Twenty-Seventh of February 2012 02:06:36 AM
10SELECT TO_CHAR(SYSDATE, 'FMDay, DDth Month YYYY','NLS_DATE_LANGUAGE=Spanish') FROM DUAL; -- Returns Lunes, 27TH Febrero 2012
12TO_CHAR(sysdate, 'Day', 'nls_date_language=Dutch') TODAY_DT
13FROM DUAL; -- Returns Monday    Maandag
TO_DATE function converts a character string representing a date to a date value according to the fmt specified. If fmt is omitted, the format is DD-MON-YY. The nlsparams parameter has the same purpose in this function as in the TO_CHAR function for date conversion.
The DD-MON-YY format is usually used to insert a date value. If a date must be entered in a format other than the default format, for example, with another century, or a specific time, you must use the TO_DATE function.
1SELECT TO_DATE('2012/02/27', 'yyyy/mm/dd') FROM DUAL;
3SELECT TO_DATE('20120227', 'yyyymmdd') FROM DUAL;
4SELECT TO_DATE('February 27, 2012, 04:00 P.M.','Month dd, YYYY, HH:MI A.M.')FROM DUAL;
Similarly TO_TIMESTAMP used to convert char of CHAR, VARCHAR2, NCHAR, or NVARCHAR2 datatype to a value of TIMESTAMP datatype.
2SELECT TO_TIMESTAMP('February 27, 2012, 04:12:34 P.M.','Month dd, YYYY, HH:MI:SS A.M.')FROM DUAL;
3SELECT TO_TIMESTAMP ('27-Feb-12 04:12:34.123000', 'DD-Mon-RR HH24:MI:SS.FF') FROM DUAL;
Arithmetic with Dates:
Here are 3 golden roles:
  1. You can compare DATE values using the standard comparison operators such as =, !=, >, etc.
  2. You can subtract two DATE values, and the result is a FLOAT which is the number of days between the two DATE values. In general, the result may contain a fraction because DATE also has a time component. For obvious reasons, adding, multiplying, and dividing two DATE values are not allowed.
  3. You can add and subtract constants to and from a DATE value, and these numbers will be interpreted as numbers of days. For example, SYSDATE+1 will be tomorrow. You cannot multiply or divide DATE values.
Date Functions:
Date functions operate on Oracle dates. All date functions return a value of DATE data type except MONTHS_BETWEEN, which returns a numeric value.
• MONTHS_BETWEEN (date1, date2):
This function returns the number of months between date1 and date2. The result can be positive or negative. If date1 is later than date2, the result is positive; if date1 is earlier than date2, the result is negative. The noninteger part of the result represents a portion of the month.
• ADD_MONTHS(date, n):
This function adds n number of calendar months to date. The value of n must be an integer and can be negative.
• NEXT_DAY(date, ‘char’):
This function finds the date of the next specified day of the week (‘char’) following date. The value of char may be a number representing a day or a character string.
• LAST_DAY(date):
This function finds the date of the last day of the month that contains date.
• ROUND(date[,'fmt']):
This function returns date rounded to the unit specified by the format model fmt. If the format model fmt is omitted, date is rounded to the nearest day.
• TRUNC(date[, 'fmt']):
This function returns date with the time portion of the day truncated to the unit specified by the format model fmt. If the format model fmt is omitted, date is truncated to the nearest day.
02SELECT MONTHS_BETWEEN(SYSDATE , TO_DATE('01-JAN-2012','DD-MON-YYYY')) FROM DUAL; --Returns months between Sysdate and '01-JAN-2012' (1.84580906511350059737156511350059737157)
03SELECT ADD_MONTHS (SYSDATE, 1) FROM DUAL; -- Move ahead one month (27-MAR-12)
04SELECT ADD_MONTHS (SYSDATE, -4) FROM DUAL; -- Move backward four months (27-OCT-11)
05SELECT NEXT_DAY (SYSDATE, 'MONDAY') FROM DUAL;  -- Go to next Monday after today’s date (05-MAR-12)
06SELECT LAST_DAY (SYSDATE) FROM DUAL;  -- Returns the last day of the month (29-FEB-12)
EXTRACT Function:
An EXTRACT datetime function extracts and returns the value of a specified datetime field from a datetime or interval value expression. When you extract a TIMEZONE_REGION or TIMEZONE_ABBR (abbreviation), the value returned is a string containing the appropriate time zone name or abbreviation
The syntax of EXTRACT function is
Have  a nice Day!

Max number in a Varchar column!

Well, to find the maximum number in a VARCHAR2 Column is bit tricky and we can find it in many ways. An example can be to find the maximum number in the Segment1 column in mtl_system_items_b table. Here is one of the best ways to find it:
1select max(to_number(segment1))
2FROM mtl_system_items_b
3where regexp_like(segment1, '^-?[[:digit:],.]*$');

PL/SQL Wrap Utility and DBMS_DDL.WRAP Function to Encrypt your PL/SQL Code

Often developers want to wrap their code to prevent the misuse of their code and also sometimes they don’t want to expose their algorithm to the world. For such cases Oracle has come up with a utility called ‘wrap utility’ (wrap.exe) which provides a way for PL/SQL developers to protect their intellectual property by making their PL/SQL code unreadable. These encryption options have long been available for other programming languages and were introduced for PL/SQL in version 7.
The wrap utility takes a readable, ASCII text file as input and converts it to a file containing byte code.  The result is that the DBA, developers or anyone with database access cannot view the source code in any readable format.

How to run?

To run the Wrap Utility, enter the wrap command at your operating system prompt using the following syntax:

wrap iname=input_file [oname=output_file]


  • iname – The name of the unencrypted PL/SQL file to be used as input (your source file).
  • oname – The name of the output file.  This file will be encrypted.


  • Leave no space around the equal signs because spaces delimit individual arguments.
  • The wrap command requires only one argument, which is iname=input_file where input_file is the name of the Wrap Utility input file. You need not specify the file extension because it defaults to sql.
  • However, you can specify a different file extension such as ‘wrap iname=/mydir/myfile.src’
  • Optionally, the wrap command takes a second argument, which is oname=output_file where output_file is the name of the Wrap Utility output file. You need not specify the output file because its name defaults to that of the input file and its extension defaults to plb (PL/SQL binary).
  • Generally, the output file is much larger than the input file.
  • The input file can contain any combination of SQL statements. However, the Wrap Utility encrypts only the CREATE statements, which define subprograms, packages, or object types.
  • If your input file contains syntax errors, the Wrap Utility detects and reports them. However, the Wrap Utility cannot detect semantic errors because it does not resolve external references.
To test the Wrap Utility, let’s first create a procedure (test_wrap_proc.sql)
03  CURSOR c_languages
04  IS
09  DBMS_OUTPUT.PUT_LINE('----------------------------');
10  FOR r_languages IN c_languages LOOP
11  DBMS_OUTPUT.PUT_LINE(r_languages.ISO_LANGUAGE||'---'||r_languages.NLS_TERRITORY);
13END test_wrap_proc;
Then go to the command prompt and run the Wrap Utility as shown below.

It will create an encrypted file (test_wrap_proc.plb) as shown below.
01CREATE OR REPLACE PROCEDURE test_wrap_proc wrapped
20181 10b
To run and view the results of this encrypted file, go to SQL*Plus and compile the procedure.

Oracle has given few Guidelines for Wrapping as below:

  • Wrap only the body of a package or object type, not the specification. This allows other developers to see the information they must use the package or type, but prevents them from seeing its implementation.
  • Wrap code only after you have finished editing it. You cannot edit PL/SQL source code inside wrapped files. Either wrap your code after it is ready to ship to users or include the wrapping operation as part of your build environment. To change wrapped PL/SQL code, edit the original source file and then wrap it again.
  • Before distributing a wrapped file, view it in a text editor to be sure that all important parts are wrapped.

There are few Limitations also:

  • Wrapping is not a secure method for hiding passwords or table names.
  • Wrapping does not hide the source code for triggers. To hide the workings of a trigger, write a one-line trigger that invokes a wrapped subprogram.
  • Wrapping does not detect syntax or semantic errors.
  • Wrapped PL/SQL units are upward-compatible between Oracle Database releases, but are not downward-compatible. For example, you can load files processed by the V8.1.5 wrap utility into a V8.1.6 Oracle Database, but you cannot load files processed by the V8.1.6 wrap utility into a V8.1.5 Oracle Database.

Using DBMS_DDL for Obfuscation:

In prior releases you have been able to use the wrap utility to obfuscate code. However any program unit created dynamically by using EXECUTE IMMEDIATE or DBMS_SQL is not automatically wrapped. This need has been satisfied in the Oracle10gR2.
The DBMS_DDL package contains the WRAP and   CREATE_WRAPPED   methods for obfuscating a single PL/SQL unit that can only be a package specification, package body, function, procedure, type specification, or type body. 
The wrap functions provide a mechanism for obfuscating dynamically generated PL/SQL program units that are created in a database.

Benefits of Dynamic Obfuscation:

Added security to dynamically generated code.
    • Ability to create wrapped code without compiling the program unit
    • Ability to create obfuscated program units on the fly using end-user specification
Use the overloaded WRAP function with EXECUTE IMMEDIATE to create the wrapped code, as the following example illustrates:
02  v_Procedure VARCHAR2(4000);
04  v_Procedure :=  'CREATE OR REPLACE PROCEDURE test_wrap_proc '
05                  || 'AS '
06                  || 'CURSOR c_languages '
07                  || 'IS '
08                  || 'SELECT ISO_LANGUAGE,NLS_TERRITORY '
09                  || 'FROM FND_LANGUAGES; '
10                  || 'BEGIN '
11                  || 'FOR r_languages IN c_languages LOOP '
12                  || 'DBMS_OUTPUT.PUT_LINE(r_languages.ISO_LANGUAGE||r_languages.NLS_TERRITORY); '
13                  || 'END LOOP; '
14                  || 'END test_wrap_proc; ';
To see the wrapped procedure, select the text from the USER_SOURCE view.
1SELECT text
2FROM user_source WHERE lower(name) = 'test_wrap_proc';

Now the million dollar question is– Can we unwrap a PL/SQL Code?

Please note: there is no legal way to unwrap a *.plb binary file (as said by Oracle). You are supposed to backup and keep your source files after wrapping them. However this world is filled with lots of skilled hackers and it is not impossible to unwrap PL/SQL Code. If you are more interested, you can check out the below links which contain very interesting discussion about this topic.
  • MOS Note: Wrap Utility – Unwrap PL/SQL Code? [ID 376303.1]
Oracle® Database PL/SQL Language Reference 11g Release 1 (11.1)
Dibyajyoti Koch

Table Partitioning in Oracle:Divide and Conquer!

Partitioning is a divide-and-conquer approach to improving Oracle maintenance and SQL performance. As the number of rows in table increases, the performance impacts will increase and Backup and recovery process may take longer time than usual and sql queries that affecting entire table will take much longer time. We can reduce the performance issue causing by large tables through separating the rows of a single table into multiple parts. Dividing a table’s data in this manner is called partitioning the table. The table that is partitioned is called a partitioned table, and the parts are called partitions.
Important note here is that SQL queries and DML statements do not need to be modified in order to access partitioned tables. After partitions are defined, DDL statements can access and manipulate individual partitions rather than entire tables or indexes. This is how partitioning can simplify the manageability of large database objects. Also, partitioning is entirely transparent to applications.
Each partition of a table or index must have the same logical attributes, such as column names, datatypes, and constraints. But each partition can have separate physical attributes such as pctfree, pctused, and tablespaces.
Advantages of using Partition’s in Table
  • The performance of queries against the tables may improve because Oracle may have to search only one partition (one part of the table) instead of the entire table to resolve a query.
  • The table may be easier to manage. Because the partitioned table’s data is stored in multiple parts, it may be easier to load and delete data in the partitions than in the large table.
  • Backup and recovery operations may perform better. Because the partitions are smaller than the partitioned table, you may have more options for backing up and recovering the partitions than you would have for a single large table.
Types of Partitioning Methods
1] RANGE Partitioning
The most basic type of partitioning for a table is called range partitioning. Range partitioning divides a table into partitions based on a range of values. You can use one or more columns to define the range specification for the partitions. Oracle automatically uses the upper bound of the next lower VALUES LESS THAN value as the lower bound of a partition.
01CREATE TABLE sales_range
02(salesman_id     NUMBER(5),
03salesman_name    VARCHAR2(30),
04sales_amount     NUMBER(10),
05sales_date       DATE)
06PARTITION BY RANGE(sales_date)
08PARTITION sales_jan2000 VALUES LESS THAN(TO_DATE('02/01/2000','DD/MM/YYYY')),
09PARTITION sales_feb2000 VALUES LESS THAN(TO_DATE('03/01/2000','DD/MM/YYYY')),
10PARTITION sales_mar2000 VALUES LESS THAN(TO_DATE('04/01/2000','DD/MM/YYYY')),
11PARTITION sales_apr2000 VALUES LESS THAN(TO_DATE('05/01/2000','DD/MM/YYYY'))
2] HASH Partitioning
Under this type of partitioning, the records in a table are partitioned based of a Hash value found in the value of the column that is used for partitioning. “Hash Partitioning” does not have any logical meaning to the partitions as do the range partitioning.
To create a hash partition, use the PARTITION BY HASH clause in place of PARTITION BY RANGE.
1CREATE TABLE sales_hash
2(salesman_id  NUMBER(5),
3salesman_name VARCHAR2(30),
4sales_amount  NUMBER(10),
5week_no       NUMBER(2))
6PARTITION BY HASH(salesman_id)
Use hash partitioning if your data does not easily lend itself to range partitioning, but you would like to partition for performance and manageability reasons.
3] List Partitioning
List partitioning enables you to explicitly control how rows map to partitions by specifying a list of discrete values for the partitioning key in the description for each partition. The advantage of list partitioning is that you can group and organize unordered and unrelated sets of data in a natural way. For a table with a region_state column as the partitioning key, the sales_west partition might contain values like ‘California’, ‘Hawaii’ etc.
01CREATE TABLE sales_list
02(salesman_id  NUMBER(5),
03salesman_name VARCHAR2(30),
04sales_state   VARCHAR2(20),
05sales_amount  NUMBER(10),
06sales_date    DATE)
07PARTITION BY LIST(sales_state)
09PARTITION sales_west VALUES('California', 'Hawaii'),
10PARTITION sales_east VALUES ('New York', 'Virginia', 'Florida'),
11PARTITION sales_central VALUES('Texas', 'Illinois'),
Creating Subpartitions
You can create subpartitions—that is, partitions of partitions. You can use subpartitions to combine all types of partitions: range partitions, list partitions, and hash partitions. For example, you can use hash partitions in combination with range partitions, creating hash partitions of the range partitions. For very large tables, this composite partitioning may be an effective way of separating the data into manageable and tunable divisions.
Indexing a partitioned table:
When you index a table, you can partition the index just as you partition the table itself. This works because indexes are separate database objects. Partitioning the index generates the same benefits as a partitioned table–improved performance, reduced maintenance time, and increased availability. Many applications use a concept called equipartitioning to increase the total value of partitioned tables and indexes. With equipartitioning, you have the same partitions for an index as you have for its table–the same number, partitioning columns, and partition bounds. A partitioned table can have both partitioned and non-partitioned indexes on it.
Modify characteristics of partitions:
Add a partition ALTER TABLE ADD PARTITION partition_name VALUES LESS THAN value storage_parameters
Move a partition ALTER TABLE MOVE PARTITION tablespace
Rename a partition ALTER TABLE RENAME PARTITION original_partition_name TO new_partition_name
Drop a partition ALTER TABLE DROP PARTITION partition_name
Truncate a partition ALTER TABLE TRUNCATE PARTITION partition_name
The use of partition-extended table names has the following restrictions:
  • A partition-extended table name cannot refer to a remote schema object.
  • The partition-extended table name syntax is not supported by PL/SQL.
  • A partition extension must be specified with a base table. No synonyms, views, or any other schema objects are allowed.



What is PL/SQL?

PL/SQL is a procedural language that has both interactive SQL and procedural programming language constructs such as iteration, conditional branching.

What are the components of a PL/SQL Block?

Declarative part
Executable part
Exception part

What are the datatypes a available in PL/SQL?

Some scalar data types such as NUMBER, VARCHAR2, DATE, CHAR, LONG, BOOLEAN. Some composite data types such as RECORD & TABLE.

What are % TYPE and % ROWTYPE? What are the advantages of using these over datatypes?

% TYPE provides the data type of a variable or a database column to that variable.
% ROWTYPE provides the record type that represents a entire row of a table or view or columns selected in the cursor.
The advantages are:
I. Need not know about variable’s data type
ii. If the database definition of a column in a table changes, the data type of a variable changes accordingly.

What is difference between % ROWTYPE and TYPE RECORD?

% ROWTYPE is to be used whenever query returns an entire row of a table or view. TYPE RECORD is to be used whenever query returns columns of different table or views and variables.

Explain the two types of Cursors?

There are two types of cursors, Implicit Cursor and Explicit Cursor.
PL/SQL uses Implicit Cursors for queries.
User defined cursors are called Explicit Cursors. They can be declared and used.

What are the cursor attributes used in PL/SQL?

% ISOPEN – Used to check whether a cursor is open or not.
% ROWCOUNT – Used to check the number of rows fetched/updated/deleted.
% FOUND – Used to check whether cursor has fetched any row. True if rows are fetched.
% NOT FOUND – Used to check whether cursor has fetched any row. True if no rows are fetched.

What is a cursor for loop?

Cursor for loop implicitly declares %ROWTYPE as loop index, opens a cursor, fetches rows of values from active set into fields in the record and closes when all the records have been processed.

What is the difference between implicit and explicit cursors?

An explicit cursor is declared opened and fetched from in the program block where as an implicit cursor is automatically generated for SQL statements that process a single row only.

What are the different types of joins available in Oracle?
Equi Join: When primary and foreign key relationship exists between the tables that are going to be joined.
Self Join: If comparison comes in a single table
Cartesian Join: When tables are joined without giving any join condition.
Inner Join: The resultant set includes all the rows that satisfy the join condition.
Outer Join: The resultant set includes the rows which doesn’t satisfy the join condition.  The outer join operator Plus sign (+) will be included in the join condition.

What are SQLCODE and SQLERRM and why are they important for PL/SQL developers?

SQLCODE returns the value of the error number for the last error encountered. The SQLERRM returns the actual error message for the last error encountered. They can be used in exception handling to report, or, store in an error log table, the error that occurred in the code. These are especially useful for the WHEN OTHERS exception.

What is an autonomous transaction?

An autonomous transaction is an independent transaction that is initiated by another transaction (the parent transaction). An autonomous transaction can modify data and commit or rollback independent of the state of the parent transaction.

What is the difference between View and Materialized view?

Materialized view will not be refreshed every time you query the view. So to have good performance when data is not changed so rapidly, we use Materialized views rather than normal views which always fetches data from tables every time you run a query on it.

What is dynamic SQL?

Dynamic SQL allows you to construct a query, a DELETE statement, a CREATE TABLE statement, or even a PL/SQL block as a string and then execute it at runtime.

Can you use COMMIT in a trigger?

Yes but by defining an autonomous transaction.

What is the difference between anonymous blocks and stored procedures?

Anonymous block is compiled only when called. Stored procedure is compiled and stored in database with the dependency information as well. Former is PL/SQL code directly called from an application. Latter is stored in database. Former has declare statement. Latter doesn’t.

What is a package spec and package body? Why the separation?

Spec declares public constructs. Body defines public constructs, additionally declares and defines Private constructs.
Separation helps make development easier. Dependency is simplified. You can modify body without invalidating dependent objects.

What is Correlated Subquery?

Correlated Subquery is a subquery that is evaluated once for each row processed by the parent statement. Parent statement can be Select, Update or Delete.

What is Sequence?

Sequences are used for generating sequence numbers without any overhead of locking. Drawback is that after generating a sequence number if the transaction is rolled back, then that sequence number is lost.

What is SQL Deadlock?

Deadlock is a unique situation in a multi user system that causes two or more users to wait indefinitely for a locked resource. First user needs a resource locked by the second user and the second user needs a resource locked by the first user. To avoid dead locks, avoid using exclusive table lock and if using, use it in the same sequence and use Commit frequently to release locks.

What is SQL*Loader?
SQL*Loader is a product for moving data in external files into tables in an Oracle database. To load data from external files into an Oracle database, two types of input must be provided to SQL*Loader: the data itself and the control file.

What is the use of CASCADE CONSTRAINTS?
When this clause is used with the DROP command, a parent table can be dropped even when a child table exists.

Explain forward declaration used in functions?
A forward declaration means that modules (procedures and functions) are declared in advance of their actual body definition. This declaration makes that module available to be called by other modules even before the program’s body is defined. A forward declaration consists simply of the module header, which is just the name of the module followed by the parameter list (and a RETURN clause in case the module is a function), no more no less.
Forward declarations are required in one specific situation: mutual recursion.

What are SQLCODE and SQLERRM and why are they important for PL/SQL developers?
SQLCODE returns the value of the error number for the last error encountered. The SQLERRM returns the actual error message for the last error encountered. They can be used in exception handling to report, or, store in an error log table, the error that occurred in the code. These are especially useful for the WHEN OTHERS exception.

What is the difference between Truncate and Delete Commands?

TRUNCATE is a DDL command whereas DELETE is a DML command. Hence DELETE operation can be rolled back, but TRUNCATE operation cannot be rolled back. WHERE clause can be used with DELETE and not with TRUNCATE.

What is the Purpose of HAVING Clause?
The HAVING clause is used in combination with the GROUP BY clause. It can be used in a SELECT statement to filter the records that a GROUP BY returns.

What is INLINE View in SQL?

The inline view is a construct in Oracle SQL where you can place a query in the SQL FROM, clause, just as if the query was a table name.

While creating a sequence, what does cache and nocache options mean?
With respect to a sequence, the cache option specifies how many sequence values will be stored in memory for faster access.

Does the view exist if the table is dropped from the database?
Yes, in Oracle, the view continues to exist even after one of the tables (that the view is based on) is dropped from the database. However, if you try to query the view after the table has been dropped, you will receive a message indicating that the view has errors.

What is an Index?
An index is a performance-tuning method of allowing faster retrieval of records. An index creates an entry for each value that appears in the indexed columns. By default, Oracle creates B-tree indexes.

What types of index data structures can you have?
An index helps to faster search values in tables. The three most commonly used index-types are:
  • B-Tree: builds a tree of possible values with a list of row IDs that have the leaf value. Needs a lot of space and is the default index type for most databases.
  • Bitmap: string of bits for each possible value of the column. Each bit string has one bit for each row. Needs only little space and is very fast. (However, domain of value cannot be large, e.g. SEX(m,f); degree(BS,MS,PHD)
  • Hash: A hashing algorithm is used to assign a set of characters to represent a text string such as a composite of keys or partial keys, and compresses the underlying data. Takes longer to build and is supported by relatively few databases.

What is the difference between a “where” clause and a “having” clause?
“Where” is a kind of restriction statement. You use where clause to restrict all the data from DB. Where clause is used before result retrieving. But Having clause is using after retrieving the data. Having clause is a kind of filtering command.

Can a view be updated/inserted/deleted? If Yes – under what conditions?

A View can be updated/deleted/inserted if it has only one base table if the view is based on columns from one or more tables then insert, update and delete is not possible.

What is tkprof and how is it used?
The tkprof tool is a tuning tool used to determine cpu and execution times for SQL statements. You use it by first setting timed_statistics to true in the initialization file and then turning on tracing for either the entire database via the sql_trace parameter or for the session using the ALTER SESSION command. Once the trace file is generated you run the tkprof tool against the trace file and then look at the output from the tkprof tool. This can also be used to generate explain plan output.

What is explain plan and how is it used?
The EXPLAIN PLAN command is a tool to tune SQL statements. To use it you must have an explain_table generated in the user you are running the explain plan for. This is created using the utlxplan.sql script. Once the explain plan table exists you run the explain plan command giving as its argument the SQL statement to be explained. The explain_plan table is then queried to see the execution plan of the statement. Explain plans can also be run using tkprof.

What are the Lock types?
Share Lock: It allows the other users for only reading not to insert or update or delete.
Exclusive Lock: Only one user can have the privileges of insert or update and delete of particular object, others can only read.
Update Lock: Multiple user can read, update delete .

What is Pragma EXECPTION_INIT? Explain the usage?

The PRAGMA EXECPTION_INIT tells the complier to associate an exception with an oracle error.
E.g. PRAGMA EXCEPTION_INIT (exception name, oracle error number)

What is Raise_application_error?
Raise_application_error is a procedure of package DBMS_STANDARD which allows to issue a user_defined error messages from stored sub-program or database trigger.

What are the modes for passing parameters to Oracle?

There are three modes for passing parameters to subprograms
IN – An In-parameter lets you pass values to the subprogram being called. In the subprogram it acts like a constant and cannot be assigned a value.
OUT – An out-parameter lets you return values to the caller of the subprogram. It acts like an initialized variable its value cannot be assigned to another variable or to itself.
INOUT – An in-out parameter lets you pass initial values to the subprogram being called and returns updated values to the caller.

What is the difference between Package, Procedure and Functions?
A package is a database objects that logically groups related PL/SQL types, objects, and Subprograms.
Procedure is a sub program written to perform a set of actions and can return multiple values.
Function is a subprogram written to perform certain computations and return a single value.
Unlike subprograms packages cannot be called, passed parameters or nested.

How do you make a Function and Procedure as a Private?
Functions and Procedures can be made private to a package by not mentioning their declaration in the package specification and by just mentioning them in the package body.

What is Commit, Rollback and Save point?
Commit – Makes changes to the current transaction permanent. It erases the savepoints and releases the transaction locks.
Savepoint –Savepoints allow to arbitrarily hold work at any point of time with option of later committing. They are used to divide transactions into smaller portions.
Rollback – This statement is used to undo work.

What is the difference between DDL, DML and DCL structures?
DDL statements are used for defining data. Ex: Create, Alter, Drop, Truncate, Rename.
DML statements are used for manipulating data. Ex: Insert, update, truncate.
DCL statements are used for to control the access of data. Ex; Grant, Revoke.
TCL statements are used for data saving. Ex; Commit, Rollback, Savepoint.

What is the difference between the snapshot and synonym?
A snapshot refers to read-only copies of a master table or tables located on a remote node. A snapshot can be queried, but not updated; only the master table can be updated. A snapshot is periodically refreshed to reflect changes made to the master table. In this sense, a snapshot is really a view with periodicity.
A synonym is an alias for table, view, sequence or program unit. They are of two types private and public.

What is the difference between data types char and varchar?
Char reserves the number of memory locations mentioned in the variable declarations, even though not used (it can store a maximum of 255 bytes). Where as Varchar does not reserve any memory locations when the variable is declared, it stores the values only after they are assigned (it can store a maximum of 32767 bytes).

Can one call DDL statements from PL/SQL?
One can call DDL statements like CREATE, DROP, TRUNCATE, etc. from PL/SQL by using the “EXECUTE IMMEDATE” statement.

Tell some new features in PL/SQL in 10g?
-Compile time warnings
- Conditional compilation
- Improvement to native compilation
- Implicit conversion between CLOB and NCLOB
- Improved Overloading
- Global optimization enabled
- PLS_INTEGER range increased to 32bit

What is Overloading in PL/SQL?
Overloading is an oops concept (Object Oriented Programming). By using the same name we can write any number of Procedures or functions in a package but either number of parameters in the procedure/function must vary or parameter datatype must vary.

What is a mutating and constraining table?
“Mutating” means “changing”. A mutating table is a table that is currently being modified by an update, delete, or insert statement. When a trigger tries to reference a table that is in state of flux (being changed), it is considered “mutating” and raises an error since Oracle should not return data that has not yet reached its final state.
Another way this error can occur is if the trigger has statements to change the primary, foreign or unique key columns of the table off which it fires. If you must have triggers on tables that have referential constraints, the workaround is to enforce the referential integrity through triggers as well.

What is Nested Table?

A nested table is a table within a table. A nested table is a collection of rows, represented as a column within the main table. For each record within main table, the nested table may contain multiple rows.  In a sense, it’s a way of storing a one-to many relationship within one table.

What is Varying Array?
A varying array is a set of objects, each with the same data types. The size of the array is limited when it is created. (When the table is created with a varying array, the array is a nested table with a limited set of rows). Varying arrays also known as VARRAYS, allows storing repeated attributes in tables.

Give some most often used predefined exceptions?
a) NO_DATA_FOUND (Select Statement returns no rows)
b) TOO_MANY_ROWS (Single row Select statement returns more than 1 row)
c) INVALID_CURSOR (Illegal cursor operations occurred)
d) CURSOR_ALREADY_OPEN (If cursor is opened & we are trying to reopen it)
e) INVALID_NUMBER (Conversion of Character to number fails)
g) DUP_VAL_ON_INDEX (Attempted to insert a duplicate value)

Give some important Oracle supplied packages?
DBMS_SQL: It is used to write Procedures & Anonymous blocks that use Dynamic SQL.
DBMS_JOB: Using it, we can submit PL/SQL programs for execution, execute PL/SQL programs on a schedule, identify when programs should run, remove programs from the schedule & suspend programs from running.
DBMS_OUTPUT: This package outputs values & messages from any PL/SQL block.
UTL_FILE: With this package, you can read from & write to Operating system files
UTL_HTTP: This package allows to make HTTP Requests directly from the database.

What is Instead Of Trigger?
This trigger is used to perform DML operation directly on the underlying tables, because a view cannot be modified by normal DML Statements if it contains joins or Group Functions. These triggers are Only Row Level Triggers. The CHECK option for views is not enforced when DML to the view are performed by Instead of Trigger.

What is the Sequence of Firing Database Triggers?
a) Before Row Level Trigger
b) Before Statement Level Trigger
c) After Row Level Trigger
d) Statement Operation
e) After Statement Level Trigger

What is the Difference between PL/SQL Table & Nested Table?

PL/SQL Table: Index by Tables are not Stored in Database.
Nested Table: Nested Tables are Stored in Database as Database Columns.

What is the Difference between Nested Table & Varray?

Nested Table
a) This are Sparse

b) We can Delete its Individual Elements
c) It do not have an Upper Boundary
d) This are Stored in System Generated Table
a) This are Dense

b) We cannot Delete its Elements
c) This are Fixed Size & always need to specify the size
d) These are Stored in Tablespaces

What are the various SQL Statements?
a) Data Retrieval: Select
b) DML: Insert, Update, Delete
c) DDL: Create, Alter, Drop, Rename, Truncate
d) Transaction Control: Commit, Rollback, Savepoint
e) DCL: Grant, Revoke
f) Session Control: Alter Session, Set Role
g) System Control: Alter System
h) Embedded SQL Statements: Open, Close, Fetch & Execute.

What is Rowid?
It is a Hexadecimal Representation of a Row in a Table. Rowid can only be Changed if we ‘Enable Row Movement’ on a Partitioned Table. Rowid’s of Deleted Rows can be Reused if Transaction is Committed.

What is Partitioning?
It Enables Tables & Indexes or Index-Organized tables to be subdivided into smaller manageable Pieces & these each small Piece is called Partition.
They are of following Types:
a) Range Partitioning
b) Hash Partitioning
c) List Partitioning
d) Composite Range-Hash Partitioning

What is a Cluster?
A cluster provides an optional method of storing table data. A cluster is comprised of a group of tables that share the same data blocks, which are grouped together because they share common columns and are often used together. For example, the EMP and DEPT table share the DEPTNO column. When you cluster the EMP and DEPT, Oracle physically stores all rows for each department from both the EMP and DEPT tables in the same data blocks. You should not use Clusters for tables that are frequently accessed individually.

What is the Difference between Nested Subquery & Correlated Subquery?
Nested Subquery
a) Inner Query runs first and executes once, returning values which are to be used by the Main query or outer query

b) Outer query is driver by Inner Query
Correlated Subquery
a) A Correlated Subquery or Inner Query execute once for each candidate row considered by outer query

b) Inner Query is Driven by Outer Query

What is the Difference between Translate & Replace?
Translate function converts each character in String with specified one whereas Replace function replaces part of the string in continuity by another sub-string.

PL/SQL Collections

PL/SQL Collections

These are composite variables in PL/SQL and have internal components that you can treat as individual variables. You can pass these composite variables to subprograms as a parameters.
To create a collection or record variable, you first define a collection or record type, and then you declare a variable of that type.
  • In a collection, the internal components are always of the same data type, and are called elements. You access each element by its unique subscript. Lists and arrays are classic examples of collections.
  • In a record, the internal components can be of different data types, and are called fields. You access each field by its name. A record variable can hold a table row, or some columns from a table row. Each record field corresponds to a table column.
PL/SQL Collection Types:
PL/SQL has three collection types, whose characteristics are summarized below.
1] Associative array (or index-by table)
  • Number of Elements: Unbounded
  • Subscript Type: String or integer
  • Dense or Sparse: Either
  • Where Created: Only in PL/SQL block
2] Nested Table
  • Number of Elements: Unbounded
  • Subscript Type: Integer
  • Dense or Sparse: Starts dense, can become sparse
  • Where Created: Either in PL/SQL block or at schema level
3] Variable size Array (Varray)
  • Number of Elements: Bounded
  • Subscript Type: Integer
  • Dense or Sparse: Always Dense
  • Where Created: Either in PL/SQL block or at schema level
Unbounded means that, theoretically, there is no limit to the number of elements in the collection. Actually, there are limits, but they are very high.
Dense means that the collection has no gaps between elements—every element between the first and last element is defined and has a value (which can be NULL).
A collection that is created in a PL/SQL block is available only in that block. A nested table type or varray type that is created at schema level is stored in the database, and you can manipulate it with SQL statements.
A collection has only one dimension, but you can model a multidimensional collection by creating a collection whose elements are also collections.
Associative Arrays (Index-By Tables):
An associative array (also called an index-by table) is a set of key-value pairs. Each key is unique, and is used to locate the corresponding value.
02  -- Associative array indexed by string:
04     TYPE ODI_RUNS IS TABLE OF NUMBER  -- Associative array type
07     odi_batsman_runs  ODI_RUNS;        -- Associative array variable
08  i VARCHAR2(64);
11    -- Add new elements to associative array:
13     odi_batsman_runs('Virender Sehwag')  := 7380;
14     odi_batsman_runs('Ricky Ponting')    := 13082;
15     odi_batsman_runs('Sachin Tendulkar') := 17629;
17   -- Print associative array:
19  i := odi_batsman_runs.FIRST;
22      DBMS_Output.PUT_LINE
23  ('Total ODI Runs on Jan 2010 by ' || i || ' is ' || TO_CHAR(odi_batsman_runs(i)));
24  i := odi_batsman_runs.NEXT(i);
25    END LOOP;
26    END;
Total ODI Runs on Jan 2010 by Ricky Ponting is 13082
Total ODI Runs on Jan 2010 by Sachin Tendulkar is 17629
Total ODI Runs on Jan 2010 by Virender Sehwag is 7380
  • Like a database table, an associative array holds a data set of arbitrary size, and you can access its elements without knowing their positions in the array.
  • An associative array does not need the disk space or network operations of a database table, but an associative array cannot be manipulated by SQL statements (such as INSERT and DELETE).
  • An associative array is intended for temporary data storage.
  • To make an associative array persistent for the life of a database session, declare the associative array (the type and the variable of that type) in a package, and assign values to its elements in the package body.
Nested Tables: 
A nested table is like a one-dimensional array with an arbitrary number of elements.
Within the database, a nested table is a column type that holds a set of values. The database stores the rows of a nested table in no particular order. When you retrieve a nested table from the database into a PL/SQL variable, the rows are given consecutive subscripts starting at 1. These subscripts give you array-like access to individual rows.
A nested table differs from an array in these important ways:
  • An array has a declared number of elements, but a nested table does not. The size of a nested table can increase dynamically.
  • An array is always dense (that is, it always has consecutive subcripts). A nested array is dense initially, but it can become sparse, because you can delete elements from it.
Variable-Size Arrays (Varrays):
A variable-size array (varray) is an item of the data type VARRAY. A varray has a maximum size, which you specify in its type definition. A varray can contain a varying number of elements, from zero (when empty) to the maximum size. A varray index has a fixed lower bound of 1 and an extensible upper bound. To access an element of a varray, you use standard subscripting syntax.
02  TYPE nested_type IS TABLE OF VARCHAR2(30);
03  TYPE varray_type IS VARRAY(5) OF INTEGER;
04  v1 nested_type;
05  v2 varray_type;
07  v1 := nested_type('Shipping','Sales','Finance','Payroll');
08  v2 := varray_type(1, 2, 3, 4, 5); -- Up to 5 integers
09FOR IN v1.FIRST .. v1.LAST
10   LOOP
11  DBMS_OUTPUT.PUT_LINE('Element #' || i || 'in the nested table = ' || v1(i));
12   END LOOP;
14FOR j IN v2.FIRST .. v2.LAST
15   LOOP
16  DBMS_OUTPUT.PUT_LINE('Element #' || j || 'in the varray = ' || v2(j));
17   END LOOP;
Nested tables Vs. Varrays:
  • Nested tables are unbounded and are initially dense but can become sparse through deletions. Varrays are always bounded and never sparse.
  • When stored in the database, the order and subscripts of Nested tables are not preserved while varrays keep their ordering and subscripts.
  • Nested table data is stored in a separate store table, a system-generated database table while a  varray is stored as a single object in the database.

Autonomous Transactions in Oracle

Autonomous Transactions in Oracle
Autonomous Transaction is a new feature in ORACLE starting from 8i. It allows setting up independent transactions that can be called from within other transactions. It lets you suspend the main transaction (without committing or rolling back), perform some DML operations, commit or roll back those operations (without any effect on the main transaction), and then return to the main transaction.
Being independent of the main transaction (almost like a separate session), an autonomous transaction does not see the uncommitted changes from the main transaction. It also does not share locks with the main transaction. Changes committed by an autonomous transaction are visible to other sessions/transactions immediately, regardless of whether the main transaction is committed or not. These changes also become visible to the main transaction when it resumes, provided its isolation level is set to READ COMMITTED (which is the default).
The following types of PL/SQL blocks can be defined as autonomous transactions:
  • Stored procedures and functions.
  • Local procedures and functions defined in a PL/SQL declaration block.
  • Packaged procedures and functions.
  • Type methods.
  • Top-level anonymous blocks.
Any of the routines can be marked as autonomous simply by using the following syntax anywhere in the declarative section of the routine (putting it at the top is recommended for better readability):
Example of an autonomous transactions:
4  FOR i IN 3 .. 10 LOOP
5    INSERT INTO at_test (id, description)
6    VALUES (i, 'Description for ' || i);

Delete Duplicate Records in Oracle

Delete Duplicate Records in Oracle
There are times when duplicate rows somehow creep into a table. The best scenario to happen this is when the data is to be imported from some other table or data and the Constraints are removed so that data import successfully. Removing duplicate rows from Oracle tables with SQL can be very tricky, and there are several techniques for identifying and removing duplicate rows from tables:
01CREATE TABLE dup_test (
02    Emp_Id VARCHAR2(5),
03  Name VARCHAR2(15),
04    Phone  NUMBER);
06INSERT INTO dup_test values('100','John',473256);
07INSERT INTO dup_test values('100','John',473256);
08INSERT INTO dup_test values('101','Dave',561982);
10SELECT * FROM dup_test;
Use subquery to delete duplicate rows:
Here we see an example of using SQL to delete duplicate table rows using an SQL subquery to identify duplicate rows, manually specifying the join columns:
02   dup_test A
04  a.rowid >
05   ANY (
06     SELECT
07        B.rowid
08     FROM
09        dup_test B
10     WHERE
11        A.Emp_Id = B.Emp_Id
12     AND
13        A.Name = B.Name
14     AND
15        A.Phone = B.Phone
16        );
Use analytics to delete duplicate rows:
You can also detect and delete duplicate rows using Oracle analytic functions:
1DELETE FROM dup_test
5    WHERE rnk>1);
Use another table to delete duplicate rows:
This is the simplest method to remove duplicity.
1CREATE TABLE dup_test_1 as select distinct * from dup_test;
2DROP TABLE dup_test;
3RENAME dup_test_1 to dup_test;
Use RANK to delete duplicate rows:
This is an example of the RANK function to identify and remove duplicate rows from Oracle tables, which deletes all duplicate rows while leaving the initial instance of the duplicate row:
01DELETE FROM dup_test where rowid in
02  (
03  select "rowid" from
04  (select "rowid", rank_n from
05  (select rank() over (partition by Emp_Id order by rowid) rank_n, rowid as "rowid"
06             from dup_test
07             )
08         )
09     where rank_n > 1
The above methods are only standard methods. You can also use your own techniques to remove duplicate records.

Normalization / De-Normalization


It is the process of efficiently organizing data in a database. There are two goals of the normalization process:
  • Eliminate redundant data (for example, storing the same data in more than one table).
  • Ensure data dependencies make sense (only storing related data in a table). Both of these are worthy goals as they reduce the amount of space a database consumes and ensure that data is logically stored.
Eliminate Repeating Groups – Make a separate table for each set of related attributes, and give each table a primary key.
Eliminate Redundant Data - If an attribute depends on only part of a multi-valued key, remove it to a separate table.
Eliminate Columns Not Dependent On Key – If attributes do not contribute to a description of the key, remove them to a separate table.
Isolate Independent Multiple Relationships - No table may contain two or more 1:n or n:m relationships that are not directly related.
Isolate Semantically Related Multiple Relationships - There may be practical constrains on information that justify separating logically related many-to-many relationships.
1st Normal Form (1NF):
Def: A table (relation) is in 1NF if
1. There are no duplicated rows in the table.
2. Each cell is single-valued (i.e., there are no repeating groups or arrays).
3. Entries in a column (attribute, field) are of the same kind.
  • The order of the rows and columns are immaterial(of no importance).
  • The requirement that there be no duplicated rows in the table means that the table has a key (although the key might be made up of more than one column—even, possibly, of all the columns).
2nd Normal Form (2NF):
Def: A table is in 2NF if it is in 1NF and if all non-key attributes are dependent on all of the key.
Note: Since a partial dependency occurs when a non-key attribute is dependent on only a part of the (composite) key, the definition of 2NF is sometimes phrased as, “A table is in 2NF if it is in 1NF and if it has no partial dependencies.”
3rd Normal Form (3NF):
Def: A table is in 3NF if it is in 2NF and if it has no transitive dependencies.
Note: A transitive dependency is a type of functional dependency in which the value in a non-key field is determined by the value in another non-key field and that field is not a candidate key.
Boyce-Codd Normal Form (BCNF):
Def: A table is in BCNF if it is in 3NF and if every determinant is a candidate key.
4th Normal Form (4NF):
Def: A table is in 4NF if it is in BCNF and if it has no multi-valued dependencies. A multi-valued dependency occurs when, for each value in field A, there is a set of values for field B and a set of values for field C but fields B and C are not related.
5th Normal Form (5NF):
Def: A table is in 5NF, also called “Projection-Join Normal Form” (PJNF), if it is in 4NF and if every join dependency in the table is a consequence of the candidate keys of the table.
Domain-Key Normal Form (DKNF):
Def: A table is in DKNF if every constraint on the table is a logical consequence of the definition of keys and domains.
Denormalization is a technique to move from higher to lower normal forms of database modeling in order to speed up database access. You may apply Denormalization in the process of deriving a physical data model from a logical form.

SET operators in Oracle

SET operators in Oracle

You can combine multiple queries using the set operators UNION, UNION ALL, INTERSECT, and MINUS. All set operators have equal precedence. If a SQL statement contains multiple set operators, then Oracle Database evaluates them from the left to right unless parentheses explicitly specify another order.
The following list briefly describes the four set operations supported by Oracle SQL:
UNION ALL : Combines the results of two SELECT statements into one result set.
UNION : Combines the results of two SELECT statements into one result set, and then eliminates any duplicate rows from that result set.
MINUS : Takes the result set of one SELECT statement, and removes those rows that are also returned by a second SELECT statement.
INTERSECT : Returns only those rows that are returned by each of two SELECT statements
SQL statements containing these set operators are referred to as compound queries, and each SELECT statement in a compound query is referred to as a component query. Two SELECTs can be combined into a compound query by a set operation only if they satisfy the following two conditions:
  1. The result sets of both the queries must have the same number of columns.  
  2. The datatype of each column in the second result set must match the datatype of its corresponding column in the first result set.
Rules and Restrictions on Set Operations:
  • Column names for the result set are derived from the first SELECT.
  • If we want to use ORDER BY in a query involving set operations, we must place the ORDER BY at the end of the entire statement. The ORDER BY clause can appear only once at the end of the compound query.
  • Component queries are executed from top to bottom. If we want to alter the sequence of execution, use parentheses appropriately.
  • Set operations are not permitted on columns of type BLOB, CLOB, BFILE, and VARRAY, nor are set operations permitted on nested table columns.
  • Since UNION, INTERSECT, and MINUS operators involve sort operations, they are not allowed on LONG columns. However, UNION ALL is allowed on LONG columns.

No comments:

Post a Comment