Sunday, November 29, 2015

Oracle SQL and PL/SQL Interview Questions Advanced

What is a cursor ? ( Basic)
- Name or handle to a private SQL area where Oracle parses and fetches query results.
How to control how many cursors are open ?(Intermediate)
- Set OPEN_CURSORS parameter in initialization parameters.
What is shared SQL ? (Intermediate)
-Oracle recognizes similar statements. The SQL area is used many times for similar statements.
What is Parsing ? (Intermediate)
- Syntax checking, privileges checking, allocating Private SQL Area.
What is the difference between anonymous blocks and stored procedures ? ( Basic)
- 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 are the advantages of procedures ? ( Basic)
- Loaded once and used many times
- Performance better coz all SQL stmts are sent in one go from the application to the database
- Security ( no object privileges are given directly )
- Invoker's rights possible
- Data integrity, productivity
What are standalone procedures ? (Basic)
- Those that are not part of package
How is a PL/SQL program stored in database ? (Advanced)
- Parsed code is stored. It's called P-code
How is a PL/SQL program executed ?(Advanced)
- Prior to Oracle 9i, we have only bytecode and a virtual machine in the database runs it. Later versions have faster native code execution.
- PL/SQL engine is the main component that executes procedural stmt and passes the SQL to the SQL statement executor.
What are the advantages and disadvantages of DBMS_SQL ? (Intermediate)
- It has all the advantages of dynamic sql .. like runtime construction of sql, DDL statements can be executed.
- Its advantage over EXECUTE IMMEDIATE is it can Describe objects
- It's kind of bulky and difficult compared to EXECUTE IMMEDIATE.
What is a package spec and package body ? Why the separation ? ( Basic)
- 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 are the advantages of Packages ? ( Basic)
- Encapsulation of code logic
- Privileges to objects can be controlled
- Loaded once into memory , used subsequently.
- Dependency simplified
- Public/private procs, functions, variables
How do you handle exceptions for bulk operations ? (Intermediate)
- Use the SAVE EXCEPTIONS clause ( FORALL index IN bound_clause SAVE EXCEPTIONS LOOP ... END LOOP )
- Use 'Exceptions When Others' to handle the exceptions
- SQL%BULK_EXCEPTIONS(i).ERROR_CODE,
SQL%BULK_EXCEPTIONS(i).ERROR_INDEX
SQL%BULK_EXCEPTIONS.COUNT
Tell some tips to avoid performance problems in PL/SQL. (Intermediate to Advanced)
- Use FORALL instead of FOR, and use BULK COLLECT to avoid looping many times
- Tune SQL statements to avoid CPU overhead
- Use NOCOPY for OUT and IN OUT if the original value need not be retained. Overhead of keeping a copy of OUT is avoided.
- Reorder conditional tests to put least expensive ones first
- Minimize datatype conversions => Assign data to exact same type variables
- Use PLS_INTEGER for computation intensive code. NUMBER, INTEGER maintain precision and scale but not optimized for performance as additional checks are made to maintain precision and scale.
- Do not use subtypes like POSITIVE, NATURAL, INTEGER as they have additional checks
- Use BINARY_FLOAT, BINARY_DOUBLE
- EXECUTE IMMEDIATE is faster than DBMS_SQL
How to know PL/SQL compile parameters ?(Advanced)
- SHOW PARAMETERS PLSQL
- ALL_PLSQL_OBJECT_SETTINGS
What is MERGE ?( Basic)
- Combination of INSERT and UPDATE
Tell some new features in PL/SQL in 10g (Intermediate to Advanced)
- Regular expression functions REGEXP_LIKE , REGEXP_INSTR, REGEXP_REPLACE, and REGEXP_SUBSTR
- Compile time warnings
- Conditional compilation
- Improvement to native compilation
- BINARY_INTEGER made similar to PLS_INTEGER
- INDICES OF , VALUES OF in FORALL lets you work on non-consecutive indices
- Quoting mechanism . Instead of quoting single quotes twice every time, give your own delimiter to go on using single quotes.
Ex: q'!I'm a string, you're a string.!'
- Flashback Query functions. SCN_TO_TIMESTAMP, TIMESTAMP_TO_SCN
- Implicit conversion between CLOB and NCLOB
- Improved Overloading
- New datatypes BINARY_FLOAT, BINARY_DOUBLE
- Global optimization enabled
- PLS_INTEGER range increased to 32bit
- DYNAMIC WRAP using DBMS_DDL
What is a sequence ? (Basic)
- A database object that offers high-speed access to an integer value
- Guaranteed to be unique (within that sequence).
-Used commonly to generate Primary key values

Thursday, October 15, 2015

New PL SQL Interview Questions - Entry Level Interview Questions for Database Developers

SQL PL/SQL Question 1

How to display row number with records?
Select rownum, ename from emp;

SQL PL/SQL Question 2

How to view version information in Oracle?
Select banner from v$version;

SQL PL/SQL Question 3

How to find the second highest salary in emp table?
select min(sal) from emp a
where 1 = (select count(*) from emp b where a.sal <>

SQL PL/SQL Question 4

How to delete the duplicate rows from a table?
create table t1 ( col1 int, col2 int, col3 char(1) );
insert into t1 values(1,50, ‘a’);
insert into t1 values(1,50, ‘b’);
insert into t1 values(1,89, ‘x’);
insert into t1 values(1,89, ‘y’);
insert into t1 values(1,89, ‘z’);
select * from t1;

Col1Col2Col2
150a
150b
289x
289y
289z

delete from T1
where rowid <> ( select max(rowid)
from t1 b
where b.col1 = t1.col1
and b.col2 = t1.col2 ) 3 rows deleted.

select * from t1;
Col1Col2Col2
150a
289z
will do it.

SQL PL/SQL Question 5

How to select a row using indexes?
You have to specify the indexed columns in the WHERE clause of query.

SQL PL/SQL Question 6

How to select the first 5 characters of FIRSTNAME column of EMP table?
select substr(firstname,1,5) from emp

SQL PL/SQL Question 7

How to concatenate the firstname and lastname from emp table?
select firstname ‘ ‘ lastname from emp

SQL PL/SQL Question 8

What's the difference between a primary key and a unique key?
Primary key does not allow nulls, Unique key allow nulls.

SQL PL/SQL Question 9

What is a self join?
A self join joins a table to itself.

Example

SELECT a.last_name Employee, b.last_name Manager
FROM employees a, employees b
WHERE b.employee_id = a.manager_id;

SQL PL/SQL Question 10

What is a transaction and ACID?
Transaction - A transaction is a logical unit of work. It must be commited or rolled back.
ACID - Atomicity, Consistency, Isolation and Duralbility, these are properties of a transaction.

SQL PL/SQL Question 11

How to add a column to a table?
alter table t1 add sal number;
alter table t1 add middle_name varchar(20);

SQL PL/SQL Question 12

Is it possible for a table to have more than one foreign key ?
A table can have any number of foreign keys. It can have only one primary key .

SQl PL/SQL Question 13

How to display number value in words?
SQL> select sal, (to_char(to_date(sal,'j'), 'jsp')) from emp;

SQL PL/SQL Question 14

What is candidate key, alternate key, composite key.
Candidate Key A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes the primary key of the table.
Alternate KeyIf the table has more than one candidate key, one of them will become the primary key, and the rest are called alternate keys.
Composite Key: - A key formed by combining at least two or more columns is called composite key.

SQL PL/SQL Question 15

What's the difference between DELETE TABLE and TRUNCATE TABLE commands? Explain drop command.
Both Delete and Truncate will leave the structure of the table. Drop will remove the structure also.

  1. Example

    If tablename is T1.
    To remove all the rows from a table t1.
    Delete t1
    Truncate table t1
    Drop table t1.
  2. Truncate is fast as compared to Delete. DELETE will generate undo information, in case of rollback, but TRUNCATE will not.

  3. Full Table scan and index fast scan read data blocks up to high water mark and truncate resets high water mark but delete does not.So full table scan after Delete will not improve but after truncate it will be fast.
  4. Delete is DML. Because truncate is a DDL, it performs implicit commit. You cannot rollback a truncate. Any uncommitted DML changes will also be committed with the TRUNCATE.
  5. You cannot specify a WHERE clause in the TRUNCATE statement, but you can specify that in Delete.
  6. When you truncate a table the storage for the table and all the indexes can be reset back to its initial size,but a Delete will never shrink the size of the a table or its indexes.
About Dropping
Dropping a table removes the data and definition of the table. The indexes, constraints, triggers, and privileges on the table are also dropped. The action of dropping a table cannot be undone. The views, materialized views or other stored programs that reference the table are not dropped but they are marked as invalid.

SQL PL/SQL Question 16

Explain the difference between a FUNCTION, PROCEDURE and PACKAGE.
Procedures and functions are stored in compiled form in database.
Functions take zero or more parameters and return a value. Procedures take zero or more parameters and return no values.
Both functions and procedures can take or return zero or more values through their parameter lists.
Another difference between procedures and functions, other than the return value, is how they are called. Procedures are called as stand-alone executable statements:
my_procedure(parameter1,parameter2...);
Functions can be called anywhere in an valid expression :
e.g
1) IF (tell_salary(empno) < 500 ) THEN … 2) var1 := tell_salary(empno); 3) DECLARE var1 NUMBER DEFAULT tell_salary(empno); BEGIN …
Packages contain function , procedures and other data structures.
There are a number of differences between packaged and non-packaged PL/SQL programs. Package The data in package is persistent for the duration of the user’s session.The data in package thus exists across commits in the session.
If you grant execute privilege on a package, it is for all functions and procedures and data structures in the package specification. You cannot grant privileges on only one procedure or function within a package. You can overload procedures and functions within a package, declaring multiple programs with the same name. The correct program to be called is decided at runtime, based on the number or datatypes of the parameters.

SQL PL/SQL Question 17

Describe the use of %ROWTYPE and %TYPE in PL/SQL
%ROWTYPE associates a variable to an entire table row.
The %TYPE associates a variable with a single column type.

SQ PL/SQL Question 18

What are SQLCODE and SQLERRM and why are they important for PL/SQL developers?
SQLCODE returns the current database error number. These error numbers are all negative, except NO_DATA_FOUND, which returns +100.
SQLERRM returns the textual error message.. These are used in exception handling.

SQL PL/SQL Question 19

How can you find within a PL/SQL block, if a cursor is open?
By the Use of %ISOPEN cursor variable.

SQL PL/SQL Question 20

How do you debug output from PL/SQL?
By the use the DBMS_OUTPUT package.
By the use of SHOW ERROR command, but this only shows errors.
The package UTL_FILE can also be used.

SQL PL/SQL Question 21

What are the types of triggers?
  • Use Row and Statement Triggers
  • Use INSTEAD OF Triggers

    SQL PL/SQL Question 22

    Explain the usage of WHERE CURRENT OF clause in cursors ?
    It refers to the latest row fetched from a cursor in an update and delete statement.

    SQL PL/SQL Question 23

    Name the tables where characteristics of Package, procedure and functions are stored ?
    User_objects, User_Source and User_error.

    SQL PL/SQL Question 24

    What are two parts of package ?
    They consist of package specification, which contains the function headers, procedure headers, and externally visible data structures. The package also contains a package body, which contains the declaration, executable, and exception handling sections of all the bundled procedures and functions.

    SQL PL/SQL Question 25

    What are two virtual tables available during database trigger execution ?
    The table columns are referred as OLD.column_name and NEW.column_name.
    For INSERT only TRIGGERS NEW.column_name values ARE only available.
    For UPDATE only TRIGERS OLD.column_name NEW.column_name values ARE only available.
    For DELETE only TRIGGERS OLD.column_name values ARE only available.v

    SQL PL/SQL Question 26

    What is Overloading of procedures ?
    REPEATING OF SAME PROCEDURE NAME WITH DIFERENT PARAMETER LIST.

    SQL PL/SQL Question 27

    What are the return values of functions SQLCODE and SQLERRM ?
    SQLCODE returns the latest code of the error that has occurred.
    SQLERRM returns the relevant error message of the SQLCODE.

    SQL PL/SQL Question 28

    Is it possible to use Transaction control Statements such a ROLLBACK or COMMIT in Database Trigger ? Why ?
    It is not possible.,because of the side effect to transactions. You can use them indirectly by calling procedures or functions .

    SQL PL/SQL Question 29

    What are the modes of parameters that can be passed to a procedure ?
    IN, OUT, IN-OUT parameters.
  • Monday, September 14, 2015

    Must Know PL/SQL Interview Questions - Latest PL SQl Interview Questions

    1. What is PL/SQL ?
    PL/SQL is a procedural language which has interactive SQL, as well as procedural programming language constructs like conditional branching and iteration.

    2. Differentiate between % ROWTYPE and TYPE RECORD.
    % ROWTYPE is used when a query returns an entire row of a table or view.
    TYPE RECORD, on the other hand, is used when a query returns column of different tables or views.
    Eg.  TYPE r_emp is RECORD (sno smp.smpno%type,sname smp sname %type)
    e_rec smp ROWTYPE
    Cursor c1 is select smpno,dept from smp;
    e_rec c1 %ROWTYPE

    3. Explain uses of cursor.
    Cursor is a named private area in SQL from which information can be accessed. They are required to process each row individually for queries which return multiple rows.

    4. Show code of a cursor for loop.
    Cursor declares %ROWTYPE as loop index implicitly. It then opens a cursor, gets rows of values from the active set in fields of the record and shuts when all records are processed.
    Eg.  FOR smp_rec IN C1 LOOP
    totalsal=totalsal+smp_recsal;
    ENDLOOP;

    5. Explain the uses of database trigger.
    A PL/SQL program unit associated with a particular database table is called a database trigger. It is used for :
    1)Audit data modifications.
    2)Log events transparently.
    3)Enforce complex business rules.
    4)Maintain replica tables
    5)Derive column values
    6)Implement Complex security authorizations

    6. What are the two types of exceptions.
    Error handling part of PL/SQL block is called Exception. They have two types : user_defined and predefined.

    7. Show some predefined exceptions.
    DUP_VAL_ON_INDEX
    ZERO_DIVIDE
    NO_DATA_FOUND
    TOO_MANY_ROWS
    CURSOR_ALREADY_OPEN
    INVALID_NUMBER
    INVALID_CURSOR
    PROGRAM_ERROR
    TIMEOUT _ON_RESOURCE
    STORAGE_ERROR
    LOGON_DENIED
    VALUE_ERROR
    etc.

    8. Explain Raise_application_error.
    It is a procedure of package DBMS_STANDARD that allows issuing of user_defined error messages from database trigger or stored sub-program.

    9.Show how functions and procedures are called in a PL/SQL block.
    Function is called as a part of an expression.
    total:=calculate_sal(‘b644’)
    Procedure is called  as a statement in PL/SQL.
    calculate_bonus(‘b644’);

    10. Explain two virtual tables available at the time of database trigger execution.
    Table columns are referred as THEN.column_name and NOW.column_name.
    For INSERT related triggers, NOW.column_name values are available only.
    For DELETE related triggers, THEN.column_name values are available only.
    For UPDATE related triggers, both Table columns are available.

    11. What are the rules to be applied to NULLs whilst doing comparisons?
    1) NULL is never TRUE or FALSE
    2) NULL cannot be equal or unequal to other values
    3) If a value in an expression is NULL, then the expression itself evaluates to NULL except for concatenation operator (||)

    12. How is a process of PL/SQL compiled?
    Compilation process includes syntax check, bind and p-code generation processes.
    Syntax checking checks the PL/SQL codes for compilation errors. When all errors are corrected, a storage address is assigned to the variables that hold data. It is called Binding. P-code is a list of instructions for the PL/SQL engine. P-code is stored in the database for named blocks and is used the next time it is executed.

    13. Differentiate between Syntax and runtime errors.
    A syntax error can be easily detected by a PL/SQL compiler. For eg, incorrect spelling.
    A runtime error is handled with the help of exception-handling section in an PL/SQL block. For eg, SELECT INTO statement, which does not return any rows.

    14. Explain Commit, Rollback and Savepoint.
    For a COMMIT statement, the following is true:
    • Other users can see the data changes made by the transaction.
    • The locks acquired by the transaction are released.
    • The work done by the transaction becomes permanent.
    A ROLLBACK statement gets issued when the transaction ends, and the following is true.
    • The work done in a transition is undone as if it was never issued.
    • All locks acquired by transaction are released.
    It undoes all the work done by the user in a transaction. With SAVEPOINT, only part of transaction can be undone.

    15. Define Implicit and Explicit Cursors.
    A cursor is implicit by default. The user cannot control or process the information in this cursor.
    If a query returns multiple rows of data, the program defines an explicit cursor. This allows the application to process each row sequentially as the cursor returns it.

    16. Explain mutating table error.
    It occurs when a trigger tries to update a row that it is currently using. It is fixed by using views or temporary tables, so database selects one and updates the other.

    17. When is a declare statement required?
    DECLARE statement is used by PL/SQL anonymous blocks such as with stand alone, non-stored procedures. If it is used, it must come first in a stand alone file.

    18. How many triggers can be applied to a table?
    A maximum of 12 triggers can be applied to one table.

    19. What is the importance of SQLCODE and SQLERRM?
    SQLCODE returns the value of the number of error for the last encountered error whereas SQLERRM returns the message for the last error.

    20. If a cursor is open, how can we find in a PL/SQL Block?
    the %ISOPEN cursor status variable can be used.

    21. Show the two PL/SQL cursor exceptions.
    Cursor_Already_Open
    Invaid_cursor

    22. What operators deal with NULL?
    NVL converts NULL to another specified value.
    var:=NVL(var2,’Hi’);
    IS NULL and IS NOT NULL can be used to check specifically to see whether the value of a variable is NULL or not.

    23. Does SQL*Plus also have a PL/SQL Engine?
    No, SQL*Plus does not have a PL/SQL Engine embedded in it. Thus, all PL/SQL code is sent directly to database engine. It is much more efficient as each statement is not individually stripped off.

    24. What packages are available to PL/SQL developers?
    DBMS_ series of packages, such as, DBMS_PIPE, DBMS_DDL, DBMS_LOCK, DBMS_ALERT, DBMS_OUTPUT, DBMS_JOB, DBMS_UTILITY, DBMS_SQL, DBMS_TRANSACTION, UTL_FILE.

    25. Explain 3 basic parts of a trigger.
    • A triggering statement or event.
    • A restriction
    • An action
    26. What are character functions?
    INITCAP, UPPER, SUBSTR, LOWER and LENGTH are all character functions. Group functions give results based on groups of rows, as opposed to individual rows. They are MAX, MIN, AVG, COUNT and SUM.

    27. Explain TTITLE and BTITLE.
    TTITLE and BTITLE commands that control report headers and footers.

    28. Show the cursor attributes of PL/SQL.
    %ISOPEN : Checks if the cursor is open or not
    %ROWCOUNT : The number of rows that are updated, deleted or fetched.
    %FOUND : Checks if the cursor has fetched any row. It is true if rows are fetched
    %NOT FOUND : Checks if the cursor has fetched any row. It is True if rows are not fetched.


    29. What is an Intersect?
    Intersect is the product of two tables and it lists only matching rows.

    30. What are sequences?
    Sequences are used to generate sequence numbers without an overhead of locking. Its drawback is that the sequence number is lost if the transaction is rolled back.

    31. How would you reference column values BEFORE and AFTER you have inserted and deleted triggers?

    Using the keyword “new.column name”, the triggers can reference column values by new collection. By using the keyword “old.column name”, they can reference column vaues by old collection.

    32. What are the uses of SYSDATE and USER keywords?
    SYSDATE refers to the current server system date. It is a pseudo column. USER is also a pseudo column but refers to current user logged onto the session. They are used to monitor changes happening in the table.

    33. How does ROWID help in running a query faster?
    ROWID is the logical address of a row, it is not a physical column. It composes of data block number, file number and row number in the data block. Thus, I/O time gets minimized retrieving the row, and results in a faster query.

    34. What are database links used for?
    Database links are created in order to form communication between various databases, or different environments like test, development and production. The database links are read-only to access other information as well.

    35. What does fetching a cursor do?
    Fetching a cursor reads Result Set row by row.

    36. What does closing a cursor do?
    Closing a cursor clears the private SQL area as well as de-allocates memory

    37. Explain the uses of Control File.
    It is a binary file. It records the structure of the database. It includes locations of several log files, names and timestamps. They can be stored in different locations to help in retrieval of information if one file gets corrupted.

    38.  Explain Consistency
    Consistency shows that data will not be reflected to other users until the data is commit, so that consistency is maintained.


    39. Differ between Anonymous blocks and sub-programs.
    Anonymous blocks are unnamed blocks that are not stored anywhere whilst sub-programs are compiled and stored in database. They are compiled at runtime.

    40. Differ between DECODE and CASE.
    DECODE and CASE statements are very similar, but CASE is extended version of DECODE. DECODE does not allow Decision making statements in its place.
    select decode(totalsal=12000,’high’,10000,’medium’) as decode_tesr from smp where smpno in (10,12,14,16);
    This statement returns an error.

    CASE is directly used in PL/SQL, but DECODE is used in PL/SQL through SQL only.

    41. Explain autonomous transaction.
    An autonomous transaction is an independent transaction of the main or parent transaction. It is not nested if it is started by another transaction.
    There are several situations to use autonomous transactions like event logging and auditing.

    42. Differentiate between SGA and PGA.
    SGA stands for System Global Area whereas PGA stands for Program or Process Global Area. PGA is only allocated 10% RAM size, but SGA is given 40% RAM size.

    43. What is the location of Pre_defined_functions.
    They are stored in the standard package called “Functions, Procedures and Packages”

    44. Explain polymorphism in PL/SQL.
    Polymorphism is a feature of OOP. It is the ability to create a variable, an object or function with multiple forms. PL/SQL supports Polymorphism in the form of program unit overloading inside a member function or package..Unambiguous logic must be avoided whilst overloading is being done.

    45. What are the uses of MERGE?
    MERGE is used to combine multiple DML statements into one.
    Syntax : merge into tablename
    using(query)
    on(join condition)
    when not matched then
    [insert/update/delete] command
    when matched then
    [insert/update/delete] command

    46. Can 2 queries be executed simultaneously in a Distributed Database System?
    Yes, they can be executed simultaneously. One query is always independent of the second query in a distributed database system based on the 2 phase commit.

    47. Explain Raise_application_error.
    It is a procedure of the package DBMS_STANDARD that allow issuing a user_defined error messages from the database trigger or stored sub-program.

    48.  What is out parameter used for eventhough return statement can also be used in pl/sql?
    Out parameters allows more than one value in the calling program. Out parameter is not recommended in functions. Procedures can be used instead of functions if multiple values are required. Thus, these procedures are used to execute Out parameters.

    49. How would you convert date into Julian date format?
    We can use the J format string :
    SQL > select to_char(to_date(‘29-Mar-2013’,’dd-mon-yyyy’),’J’) as julian from dual;

    JULIAN

    50. Explain SPOOL
    Spool command can print the output of sql statements in a file.
    spool/tmp/sql_outtxt
    select smp_name, smp_id from smp where dept=’accounts’;
    spool off;

    Wednesday, March 4, 2015

    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.

    Monday, December 22, 2014

    PL/SQL - Triggers

    Triggers are stored programs, which are automatically executed or fired when some events occur. Triggers are, in fact, written to be executed in response to any of the following events:
    • A database manipulation (DML) statement (DELETE, INSERT, or UPDATE).
    • A database definition (DDL) statement (CREATE, ALTER, or DROP).
    • A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).
    Triggers could be defined on the table, view, schema, or database with which the event is associated.

    Benefits of Triggers

    Triggers can be written for the following purposes:
    • Generating some derived column values automatically
    • Enforcing referential integrity
    • Event logging and storing information on table access
    • Auditing
    • Synchronous replication of tables
    • Imposing security authorizations
    • Preventing invalid transactions

    Creating Triggers

    The syntax for creating a trigger is:
    CREATE [OR REPLACE ] TRIGGER trigger_name 
    {BEFORE | AFTER | INSTEAD OF } 
    {INSERT [OR] | UPDATE [OR] | DELETE} 
    [OF col_name] 
    ON table_name 
    [REFERENCING OLD AS o NEW AS n] 
    [FOR EACH ROW] 
    WHEN (condition)  
    DECLARE
       Declaration-statements
    BEGIN 
       Executable-statements
    EXCEPTION
       Exception-handling-statements
    END;
    Where,
    • CREATE [OR REPLACE] TRIGGER trigger_name: Creates or replaces an existing trigger with the trigger_name.
    • {BEFORE | AFTER | INSTEAD OF} : This specifies when the trigger would be executed. The INSTEAD OF clause is used for creating trigger on a view.
    • {INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the DML operation.
    • [OF col_name]: This specifies the column name that would be updated.
    • [ON table_name]: This specifies the name of the table associated with the trigger.
    • [REFERENCING OLD AS o NEW AS n]: This allows you to refer new and old values for various DML statements, like INSERT, UPDATE, and DELETE.
    • [FOR EACH ROW]: This specifies a row level trigger, i.e., the trigger would be executed for each row being affected. Otherwise the trigger will execute just once when the SQL statement is executed, which is called a table level trigger.
    • WHEN (condition): This provides a condition for rows for which the trigger would fire. This clause is valid only for row level triggers.

    Example:

    To start with, we will be using the CUSTOMERS table we had created and used in the previous chapters:
    Select * from customers;
    
    +----+----------+-----+-----------+----------+
    | ID | NAME     | AGE | ADDRESS   | SALARY   |
    +----+----------+-----+-----------+----------+
    |  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
    |  2 | Khilan   |  25 | Delhi     |  1500.00 |
    |  3 | kaushik  |  23 | Kota      |  2000.00 |
    |  4 | Chaitali |  25 | Mumbai    |  6500.00 |
    |  5 | Hardik   |  27 | Bhopal    |  8500.00 |
    |  6 | Komal    |  22 | MP        |  4500.00 |
    +----+----------+-----+-----------+----------+
    The following program creates a row level trigger for the customers table that would fire for INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This trigger will display the salary difference between the old values and new values:
    CREATE OR REPLACE TRIGGER display_salary_changes
    BEFORE DELETE OR INSERT OR UPDATE ON customers
    FOR EACH ROW
    WHEN (NEW.ID > 0)
    DECLARE
       sal_diff number;
    BEGIN
       sal_diff := :NEW.salary  - :OLD.salary;
       dbms_output.put_line('Old salary: ' || :OLD.salary);
       dbms_output.put_line('New salary: ' || :NEW.salary);
       dbms_output.put_line('Salary difference: ' || sal_diff);
    END;
    /
    When the above code is executed at SQL prompt, it produces the following result:
    Trigger created.
    
    Here following two points are important and should be noted carefully:
    • OLD and NEW references are not available for table level triggers, rather you can use them for record level triggers.
    • If you want to query the table in the same trigger, then you should use the AFTER keyword, because triggers can query the table or change it again only after the initial changes are applied and the table is back in a consistent state.
    • Above trigger has been written in such a way that it will fire before any DELETE or INSERT or UPDATE operation on the table, but you can write your trigger on a single or multiple operations, for example BEFORE DELETE, which will fire whenever a record will be deleted using DELETE operation on the table.

    Triggering a Trigger

    Let us perform some DML operations on the CUSTOMERS table. Here is one INSERT statement, which will create a new record in the table:
    INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
    VALUES (7, 'Kriti', 22, 'HP', 7500.00 );
    When a record is created in CUSTOMERS table, above create trigger display_salary_changes will be fired and it will display the following result:
    Old salary:
    New salary: 7500
    Salary difference:
    
    Because this is a new record so old salary is not available and above result is coming as null. Now, let us perform one more DML operation on the CUSTOMERS table. Here is one UPDATE statement, which will update an existing record in the table:
    UPDATE customers
    SET salary = salary + 500
    WHERE id = 2;
    When a record is updated in CUSTOMERS table, above create trigger display_salary_changes will be fired and it will display the following result:
    Old salary: 1500
    New salary: 2000
    Salary difference: 500
    

    Sunday, November 16, 2014

    Oracle Concepts and Architecture Interview Questions and Answers



    Interview questions and answers for Oracle Concepts and Architecture  Interview Questions and Answers
    Oracle Concepts and Architecture Interview Questions and Answers includes, Physical database, structure of Oracle Database, components of Logical database, Tablespace, SYSTEM tablespace, relationship among Database, schema, Schema Objects, Table, View, Sequence, Synonym, Private Synonyms, Public Synonyms, Index, Indexes Update, Clusters, cluster Key, Index Cluster. Synonyms, Cluster

    What are the components of Physical database structure of Oracle Database?
        ORACLE database is comprised of three types of files. One or more Data files, two are more Redo Log files, and one or more Control files.

    2.     What are the components of Logical database structure of ORACLE database?
        Tablespaces and the Database's Schema Objects.

    3.     What is a Tablespace?
        A database is divided into Logical Storage Unit called tablespaces. A tablespace is used to grouped related logical structures together.

    4.     What is SYSTEM tablespace and When is it Created?
        Every ORACLE database contains a tablespace named SYSTEM, which is automatically created when the database is created. The SYSTEM tablespace always contains the data dictionary tables for the entire database.

    5.     Explain the relationship among Database, Tablespace and Data file.
        Each databases logically divided into one or more tablespaces One or more data files are explicitly created for each tablespace.

    6.     What is schema?
        A schema is collection of database objects of a User.

    7.     What are Schema Objects ?
        Schema objects are the logical structures that directly refer to the database's data. Schema objects include tables,views,sequences,synonyms, indexes, clusters, database triggers, procedures, functions packages and database links.

    8.     Can objects of the same Schema reside in different tablespaces.?
        Yes.

    9.     Can a Tablespace hold objects from different Schemes ?
        Yes.

    10.     what is Table ?
          A table is the basic unit of data storage in an ORACLE database. The tables of a database hold all of the user accessible data. Table data is stored in rows and columns.

    11.     What is a View ?
          A view is a virtual table. Every view has a Query attached to it. (The Query is a SELECT statement that identifies the columns and rows of the table(s) the view uses.)

    12.     Do View contain Data ?
          Views do not contain or store data.

    13.     Can a View based on another View ?
        Yes.

    14.     What are the advantages of Views ?
          •Provide an additional level of table security, by restricting access to a predetermined set of rows and columns of a table.
    •Hide data complexity.
    •Simplify commands for the user.
    •Present the data in a different perpecetive from that of the base table.
    •Store complex queries.
    15.     What is a Sequence ?
        A sequence generates a serial list of unique numbers for numerical columns of a database's tables.

    16.     What is a Synonym ?
        A synonym is an alias for a table, view,sequence or program unit.

    17.     What are the type of Synonyms ?
        There are two types of Synonyms Private and Public.

    18.     What is a Private Synonyms ?
        A Private Synonyms can be accessed only by the owner.

    19.     What is a Public Synonyms ?
          A Public synonyms can be accessed by any user on the database.

    20.     What are synonyms used for ?
        Synonyms are used to : Mask the real name and owner of an object.
    Provide public access to an object
    Provide location transparency for tables,views or program units of a remote database.
    Simplify the SQL statements for database users.

    21.     What is an Index ?
        An Index is an optional structure associated with a table to have direct access to rows,which can be created to increase the performance of data retrieval. Index can be created on one or more columns of a table.

    22.     How are Indexes Update ?
        Indexes are automatically maintained and used by ORACLE. Changes to table data are automatically incorporated into all relevant indexes.

    23.     What are Clusters ?
          Clusters are groups of one or more tables physically stores together to share common columns and are often used together.

    24.     What is cluster Key ?
          The related columns of the tables in a cluster is called the Cluster Key.

    25.     What is Index Cluster ?
        A Cluster with an index on the Cluster Key.

    26.     What is Hash Cluster ?
        A row is stored in a hash cluster based on the result of applying a hash function to the row's cluster key value. All rows with the same hash key value are stores together on disk.

    27.     When can Hash Cluster used ?
        Hash clusters are better choice when a table is often queried with equality queries. For such queries the specified cluster key value is hashed. The resulting hash key value points directly to the area on disk that stores the specified rows.

    28.     What is Database Link ?
        A database link is a named object that describes a "path" from one database to another.

    29.     What are the types of Database Links?
        Private Database Link, Public Database Link & Network Database Link.

    30.     What is Private Database Link?
        Private database link is created on behalf of a specific user. A private database link can be used only when the owner of the link specifies a global object name in a SQL statement or in the definition of the owner's views or procedures.

    31.     What is Public Database Link?
        Public database link is created for the special user group PUBLIC. A public database link can be used when any user in the associated database specifies a global object name in a SQL statement or object definition.

    32.     What is Network Database link?
        Network database link is created and managed by a network domain service. A network database link can be used when any user of any database in the network specifies a global object name in a SQL statement or object definition.

    33.     What is Data Block?
        ORACLE database's data is stored in data blocks. One data block corresponds to a specific number of bytes of physical database space on disk.

    34.     How to define Data Block size?
        A data block size is specified for each ORACLE database when the database is created. A database users and allocated free database space in ORACLE datablocks. Block size is specified in INIT.ORA file and cann't be changed latter.

    35.     What is Row Chaining?
        In Circumstances, all of the data for a row in a table may not be able to fit in the same data block. When this occurs, the data for the row is stored in a chain of data block (one or more) reserved for that segment.

    36.     What is an Extent?
        An Extent is a specific number of contiguous data blocks, obtained in a single allocation, used to store a specific type of information.

    37.     What is a Segment?
        A segment is a set of extents allocated for a certain logical structure.

    38.     What are the different types of Segments?
        Data Segment, Index Segment, Rollback Segment and Temporary Segment.

    39.     What is a Data Segment?
        Each Non-clustered table has a data segment. All of the table's data is stored in the extents of its data segment. Each cluster has a data segment. The data of every table in the cluster is stored in the cluster's data segment.

    40.     What is an Index Segment?
        Each Index has an Index segment that stores all of its data.

    41.     What is Rollback Segment?
        A Database contains one or more Rollback Segments to temporarily store "undo" information.

    42.     What are the uses of Rollback Segment?
        Rollback Segments are used:
    To generate read-consistent database information during database recovery to rollback uncommitted transactions for users.

    43.     What is a Temporary Segment?
        Temporary segments are created by ORACLE when a SQL statement needs a temporary work area to complete execution. When the statement finishes execution, the temporary segment extents are released to the system for future use.

    44.     What is a Data File?
        Every ORACLE database has one or more physical data files. A database's data files contain all the database data. The data of logical database structures such as tables and indexes is physically stored in the data files allocated for a database.

    45.     What are the Characteristics of Data Files?
        A data file can be associated with only one database.Once created a data file can't change size.
    One or more data files form a logical unit of database storage called a tablespace.

    46.     What is a Redo Log?
        The set of Redo Log files for a database is collectively known as the database's redo log.

    47.     What is the function of Redo Log?
        The Primary function of the redo log is to record all changes made to data.

    48.     What is the use of Redo Log Information?
        The Information in a redo log file is used only to recover the database from a system or media failure the prevents database data from being written to a database's data files.

    49.     What does a Control file Contain?
        A Control file records the physical structure of the database. It contains the following information.
    •Database Name
    •Names and locations of a database's files and redolog files.
    •Time stamp of database creation.

    50.     What is the use of Control File?
        When an instance of an ORACLE database is started, its control file is used to identify the database and redo log files that must be opened for database operation to proceed. It is also used in database recovery.

    51.     What is a Data Dictionary?
        The data dictionary of an ORACLE database is a set of tables and views that are used as a read-only reference about the database.
    It stores information about both the logical and physical structure of the database, the valid users of an ORACLE database, integrity constraints defined for tables in the database and space allocated for a schema object and how much of it is being used.

    52.     What is an Integrity Constrains?
        An integrity constraint is a declarative way to define a business rule for a column of a table.

    53.     Can an Integrity Constraint be enforced on a table if some existing table data does not satisfy the constraint?
        No.

    54.     Describe the different type of Integrity Constraints supported by ORACLE?
        •NOT NULL Constraint - Disallows NULLs in a table's column.
    •UNIQUE Constraint - Disallows duplicate values in a column or set of columns.
    •PRIMARY KEY Constraint - Disallows duplicate values and NULLs in a column or set of columns.
    •FOREIGN KEY Constrain - Require each value in a column or set of columns match a value in a related table's UNIQUE or PRIMARY KEY.
    •CHECK Constraint - Disallows values that do not satisfy the logical expression of the constraint.

    55.     What is difference between UNIQUE constraint and PRIMARY KEY constraint?
        A column defined as UNIQUE can contain NULLs while a column defined as PRIMARY KEY can't contain Nulls.

    56.     Describe Referential Integrity?
        A rule defined on a column (or set of columns) in one table that allows the insert or update of a row only if the value for the column or set of columns (the dependent value) matches a value in a column of a related table (the referenced value). It also specifies the type of data manipulation allowed on referenced data and the action to be performed on dependent data as a result of any action on referenced data.

    57.     What are the Referential actions supported by FOREIGN KEY integrity constraint?
        UPDATE and DELETE Restrict - A referential integrity rule that disallows the update or deletion of referenced data.

    DELETE Cascade - When a referenced row is deleted all associated dependent rows are deleted.

    58.     What is self-referential integrity constraint?
        If a foreign key reference a parent key of the same table is called self-referential integrity constraint.

    59.     What are the Limitations of a CHECK Constraint?
        The condition must be a Boolean expression evaluated using the values in the row being inserted or updated and can't contain subqueries, sequence, the SYSDATE,UID,USER or USERENV SQL functions, or the pseudocolumns LEVEL or ROWNUM.

    60.     What is the maximum number of CHECK constraints that can be defined on a column?
        No Limit.

    Oracle Reports Interview Questions and Answers



    Interview questions and answers for Oracle Reports  Interview Questions and Answers
    Oracle Reports Interview Questions and Answers includes, different file extensions that are created by oracle reports, designation, lexical reference, bind reference, use of command line parameter cmd file, external pl/sql library executed, default parameter, read level consistency, term, link property sheet, place holder column, hidden column, break group, anchors, matrix object, layout editor of the report writer, term panel, anchoring object, frame & repeating frame.

    What are the different file extensions that are created by oracle reports?
        Rep file and Rdf file.

    2.     From which designation is it preferred to send the output to the printed?
        Previewer.

    3.     Is it possible to disable the parameter from while running the report?
        Yes

    4.     What is lexical reference?How can it be created?
        Lexical reference is place_holder for text that can be embedded in a sql statements.A lexical reference can be created using & before the column or parameter name.

    5.     What is bind reference and how can it carate?
        Bind reference are used to replace the single value in sql,pl/sql statements a bind reference can be careated using a (:) before a column or a parameter name.

    6.     What use of command line parameter cmd file?
        It is a command line argument that allows you to specify a file that contain a set of arguments for r20run.

    7.     Where is a procedure return in an external pl/sql library executed at the client or at the server?
        At the client.

    8.     Where is the external query executed at the client or the server?
        At the server.

    9.     What are the default parameter that appear at run time in the parameter screen?
        Destype and Desname.

    10.     Which parameter can be used to set read level consistency across multiple queries?
        Read only.

    11.     What is term?
          The term is terminal definition file that describes the terminal form which you are using r20run.

    12.     What is use of term?
          The term file which key is correspond to which oracle report functions.

    13.     Is it possible to insert comments into sql statements return in the data model editor?
          Yes.

    14.     If the maximum record retrieved property of the query is set to 10 then a summary value will be calculated?
          Only for 10 records.

    15.     What are the sql clauses supported in the link property sheet?
        Where startwith having.

    16.     To execute row from being displayed that still use column in the row which property can be used?
        Format trigger.

    17.     Is it possible to set a filter condition in a cross product group in matrix reports?
        No.

    18.     If a break order is set on a column would it effect columns which are under the column?
        No.

    19.     With which function of summary item is the compute at options required?
        percentage of total functions.

    20.     What is the purpose of the product order option in the column property sheet?
        To specify the order of individual group evaluation in a cross products.

    21.     Can a formula column be obtained through a select statement?
        Yes.

    22.     Can a formula column refered to columns in higher group?
        Yes.

    23.     How can a break order be created on a column in an existing group?
          By dragging the column outside the group.

    24.     What are the types of calculated columns available?
          Summary, Formula, Placeholder column.

    25.     What is the use of place holder column?
        A placeholder column is used to hold a calculated values at a specified place rather than allowing is to appear in the actual row where it has to appeared.

    26.     What is the use of hidden column?
        A hidden column is used to when a column has to embedded into boilerplate text.

    27.     What is the use of break group?
        A break group is used to display one record for one group ones.While multiple related records in other group can be displayed.

    28..     If two groups are not linked in the data model editor, what is the hierarchy between them?
        Two group that is above are the left most rank higher than the group that is to right or below it.

    29.     The join defined by the default data link is an outer join yes or no?
        Yes.

    30.     How can a text file be attached to a report while creating in the report writer?
        By using the link file property in the layout boiler plate property sheet.

    31.     Can a repeating frame be careated without a data group as a base?
        No.

    32.     Can a field be used in a report wihtout it appearing in any data group?
        Yes.

    33.     For a field in a repeating frame, can the source come from the column which does not exist in the data group which forms the base for the frame?
        Yes.

    34.     Is it possible to center an object horizontally in a repeating frame that has a variable horizontal size?
        Yes.

    35.     If yes,how?
        By the use anchors.
    36.     What are the two repeating frame always associated with matrix object?
        One down repeating frame below one across repeating frame.

    37.     Is it possible to split the printpreviewer into more than one region?
        Yes.

    38.     Does a grouping done for objects in the layout editor affect the grouping done in the datamodel editor?
        No.

    39.     How can a square be drawn in the layout editor of the report writer?
        By using the rectangle tool while pressing the (Constraint) key.

    40.     To display the page no. for each page on a report what would be the source & logical page no. or & of physical page no.?
        & physical page no.

    41.     What does the term panel refer to with regard to pages?
        A panel is the no. of physical pages needed to print one logical page.

    42.     What is an anchoring object & what is its use?
        An anchoring object is a print condition object which used to explicitly or implicitly anchor other objects to itself.

    43.     What is a physical page? & what is a logical page?
        A physical page is a size of a page. That is output by the printer. The logical page is the size of one page of the actual report as seen in the Previewer.

    44.     What is the frame & repeating frame?
        A frame is a holder for a group of fields. A repeating frame is used to display a set of records when the no. of records that are to displayed is not known before.