oracle related questions

Upload: yash-shah

Post on 03-Apr-2018

220 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/28/2019 Oracle related Questions

    1/33

    1Explain the difference between a data block, an extent and a segment?

    A data block is the smallest unit of logical storage for a database object. As objects grow theytake chunks of additional storage that are composed of contiguous data blocks. These groupingsof contiguous data blocks are called extents. All the extents that an object takes when grouped

    together are considered the segment of the database object.

    2Give two examples of how you might determine the structure of the table DEPT?

    Use the describe command or use the dbms_metadata.get_ddl package.

    This is the new package and function that will produce the DDL for you. In its simplest form, allyou need to do is provide an object_type and an object_name.

    The following example will generate the DLL for the DBA_TABLES view.SELECT DBMS_METADATA.GET_DDL('VIEW','DBA_TABLES') FROM dual;

    The following example will generate the DLL for the table columns dept and scott.SELECT DBMS_METADATA.GET_DDL('TABLE','DEPT','SCOTT') FROM dual;

    So basically its a utility to display DDL directly from the data dictionary.

    3Where would you look for errors from the database engine?

    In the alert log file (alert instance name.log)

    Each Oracle Instance has an Alert Log file. It is created during instance startup.It records the following info:

    When the database was started or shutdown.

    A list of all initialization parameters.

    Start up background process.

    Log sequence number LGWR is writing to.

    Information regarding log switch.

    Creation of tablespaces and undo segments.

    Commands, results of major events, database errors

    4Give the two types of tables involved in producing a star schema and the type of data theyhold? What type of index should you use on a fact table?

    Fact tables and dimension tables. A fact table contains measurements while dimension tables

    will contain data that will help describe the fact tables. A Bitmap index is used on a fact table.5Explain an ORA-01555?

    You get this error when you get a snapshot too old within rollback. Rollback records needed by areader for consistent read are overwritten by other writers.

    It can usually be solved by increasing the undo retention or increasing the size of rollbacks i.e. inAutomatic Undo Management mode, increase the setting of UNDO_RETENTION.

  • 7/28/2019 Oracle related Questions

    2/33

    6What does FLOOR function do?

    Answer: It is a function used to find the largest integer less than or equal to a specific value.FLOOR(x): Returns the largest integer less than or equal to x.

    select FLOOR (-5.2) from dual;

    FLOOR(-5.2)-----------

    -6

    7What is the difference between a Flashback Table and Flashback Drop?

    Answer: Flashback table allows u to recover 1 or more tables in specific point in time, it rolls backonly the changes made to table or tables and their dependent objects

    The following command flashes back the ORDERS and ORDER_ITEMS tables to 2:33 PM onJuly 7.FLASHBACK TABLE orders, order_items TO TIMESTAMP (JUL-07-2003, 02:33:00);

    Performs the restore operation online

    Restores all data in a specified table to a previous point in time described by a timestampor SCN

    Automatically restores all of the table attributes, such as indexes, triggers, and the likethat are necessary for an application to function with the flashed back table

    Maintains data integrity as specified by constraints

    whereas Flashback drop recovers a drop table from the recycle bin.

    8What are different types of failures?

    Answer:Statement Failure- A single database operation fails, such as DML statement-insert, update andso on. Some common problems with their solutions when statement fails:

    Access tables without appropriate privileges.Running out of spaceLogical errors

    User Process Failure- An abnormal termination of a user session. PMON checks all userprocesses to ensure if session is still connected. If session is disconnected it rolls back the

    uncommitted transaction and releases all locks.

    Network Failure- A network component between the client and the database server fails and thesession is disconnected from the database. To avoid this provide redundant network paths andadditional listener connections.

    User Error Failure- An error message is not generated, but the operations result, such asdropping a table, is not what the user intended.

  • 7/28/2019 Oracle related Questions

    3/33

    Instance Failure- It occurs when the instance shuts down without synchronizing all the data filesto the same SCN, requiring recovery operation the next time instance is started.

    Causes:Power outageHardware failureOracle background process failureSHUTDOWN ABORT

    Media Failure- It is a type of failure that results in loss of one or more datafiles, control files orredo log files.

    9What is the diff between Log Miner and Flashback Query?

    Answer:Log Miner makes use of Redo Log files to find the changed records. It makes use of DML andDDL statements to view the changes and also to reverse them if required.

    Flashback Query uses undo information present in UNDO_TABLESAPCE so that a user can see

    the contents of a table at a specified time in past.

    10 How can we determine the size of the log files.?

    Answer:

    select sum(bytes)/1024/1024 size_in_mb from v$log;

    v$log -This view contains information about redo log files like to find the filenames, groupnumbers and states of redo log files..

    11What is the result of select * from table1, table2?

    Answer:The result will be the cartesian product of the rowsThere is a common column between them but no where caluse has been specified.

    12 What is SCN?

    SCN changes for every 3 minutes in 10g and for each and every action in 9i. It resides in controlfiles and data files. CKPT (checkpoint) background process updates the SCN numbers fromcontrol files to the datafiles. SMON (system monitor) background process checks for the SCNnumbers to be same in both datafiles and control files while starting the database. If same thenonly the database is consistent. Otherwise the database will not start.

  • 7/28/2019 Oracle related Questions

    4/33

    1) How many joins are required to avoid Cartesian product?

    ans: n-1 joins for n tables

    2) Question: How do I change the password for a user in Oracle?

    To change a user's password in Oracle, you need to execute the alter usercommand.

    The syntax for changing a password is:

    alter useruser_name identified by new_password;

    user_name is the user whose password you wish to change.

    new_passwordis the new password to assign.

    For example:

    If you wanted to reset the password for a user named smithj, and you wanted to set thenew password to autumn, you would run the following command:

    alter user smithj identified by autumn;

    3) The syntax for a Lock table is:

    LOCK TABLE tables IN lock_mode MODE [NOWAIT];

    Tables is a comma-delimited list of tables.

    Lock_mode is one of:

    ROW SHAREROW EXCLUSIVESHARE UPDATESHARESHARE ROW EXCLUSIVEEXCLUSIVE.

    NoWait specifies that the database should not wait for a lock to be released.

    4) Which work faster DELETE or TRUNCATE..? Why?

    Ans: Truncate. As delete being a DML statement stores back the data in the rollback segmentwhere as Truncate does not involve any procedure for storing data as being a DDL command.

    5) Question: How can I insert multiple rows of explicit data in one SQL command in Oracle?

  • 7/28/2019 Oracle related Questions

    5/33

    Answer: You can insert multiple rows using the following syntax:

    INSERT ALLINTO mytable (column1, column2, column3) VALUES ('val1.1', 'val1.2', 'val1.3')INTO mytable (column1, column2, column3) VALUES ('val2.1', 'val2.2', 'val2.3')INTO mytable (column1, column2, column3) VALUES ('val3.1', 'val3.2', 'val3.3')

    SELECT * FROM dual;

    Example #1

    If you wanted to insert 3 rows into the suppliers table, you could run the following SQL statement:

    INSERT ALLINTO suppliers (supplier_id, supplier_name) VALUES (1000, 'IBM')INTO suppliers (supplier_id, supplier_name) VALUES (2000, 'Microsoft')INTO suppliers (supplier_id, supplier_name) VALUES (3000, 'Google')

    SELECT * FROM dual;

    Example #2

    You can also insert multiple rows into multiple tables. For example, if you wanted to insert intoboth the suppliers and customers table, you could run the following SQL statement:

    INSERT ALLINTO suppliers (supplier_id, supplier_name) VALUES (1000, 'IBM')INTO suppliers (supplier_id, supplier_name) VALUES (2000, 'Microsoft')INTO customers (customer_id, customer_name, city) VALUES (999999, 'Anderson

    Construction', 'New York')SELECT * FROM dual;

    6) Can we have an ORDER BY clause in the inner query?

    Select ., .,

    Union ALL

    Select .., ., Order By

    SELECT * FROM (SELECT ename, hiredate FROM emp ORDER BY hiredate)WHERE rownum

  • 7/28/2019 Oracle related Questions

    6/33

    WHERE dept_cd IN (SELECT dept_cd

    FROM DEPT)

    This works fine.

    SELECT *

    FROM emp

    WHERE dept_cd IN (SELECT dept_cd

    FROM DEPT

    ORDER BY dept_name)

    is invalid

    8) Difference between cursor and Ref-Cursor.

    Ans:

    CURSOR

    In cursor there are 2 types explicit and implicit cursor

    Explicit cursor

    Explicit cursors are SELECT statements that are DECLAREd explicitly in the declaration

    section of the current block or in a package specification. Use OPEN FETCH and CLOSEin the execution or exception sections of your programs.

    IMPLICIT CURSOR

    Whenever a SQL statement is directly in the execution or exception section of a PL/SQLblock you are working with implicit cursors. These statements include INSERT UPDATEDELETE and SELECT INTO statements. Unlike explicit cursors implicit cursors do notneed to be declared OPENed FETCHed or CLOSEd.

    REFERENCE CURSOR

    A cursor variable is a data structure that points to a cursor object which in turn points to

    the cursor's result set. You can use cursor variables to more easily retrieve rows in aresult set from client and server programs. You can also use cursor variables to hideminor variations in queries.

    The syntax for a REF_CURSOR type is:

    TYPE ref_cursor_names IS REF CURSOR [RETURN record_type];

  • 7/28/2019 Oracle related Questions

    7/33

    If you do not include a RETURN clause then you are declaring a weak REF CURSOR.Cursor variables declared from weak REF CURSORs can be associated with any queryat runtime. A REF CURSOR declaration with a RETURN clause defines a strong REFCURSOR. A cursor variable based on a strong REF CURSOR can be associated withqueries whose result sets match the number and datatype of the record structure afterthe RETURN at runtime.

    To use cursor variables you must first create a REF_CURSOR type then declare a cursorvariable based on that type.

    The following example shows the use of both weak and strong REF CURSORs:

    DECLARE -- Create a cursor type based on the companies table. TYPEcompany_curtype IS REF CURSOR RETURN companies ROWTYPE; -- Create thevariable based on the REF CURSOR. company_cur company_curtype; -- And now theweak general approach. TYPE any_curtype IS REF CURSOR; generic_curvarany_curtype;

    The syntax to OPEN a cursor variable is:

    OPEN cursor_name FOR select_statement;

    More Information:

    Cursor (explicit cursor) are static cursors which can be associated with onlyone SQlstatement at the same time and this statement is known when block is compiled. ACursor Variable on the other hand can be associated with different queries at runtime.

    Static Cursor are analogus to PL/SQL constants because they can only be associatedwith one runtime query whereas reference cursor are analogus to PL/SQL variables

    which can hold different values at runtime.

    Reference Cursor can have return type.

    Beacause of reference type no storage is allocated for it when it is declared. Before it canbe used it needs to point to a valid area of memory which can be created either byallocating it to the client-side program or on the server by PL/SQL engine.

    A REF CURSOR can be of Two type Strongly Typed Cursorand Weakly TypedCursor

    Ex:

    TYPE ref_type_name IS REF CURSOR RETURN return_type;

    return_type represents a record in the database

    9)In which system table i can found that how many cursors are currently open in the database?

    http://www.geekinterview.com/question_details/24980http://www.geekinterview.com/question_details/24980
  • 7/28/2019 Oracle related Questions

    8/33

    Ans: Use the V$OPEN_CURSORview to know how many cursors are currently open in the

    database

    10) What is the difference between sql/pl-sql/embedded?

    Ans:

    SQL is a structured query language.

    Used to perform operations such as retrieval updating insertions etc. on database.

    PL/SQL is a Programming language which is an extension for SQL with control structures added

    to them. Number of SQL statements can be written together In

    PL/SQL.

    Embedded SQL is nothing but embedding SQL statements in high level languages like C C++

    etc.

    Embedded SQL - SQL statements are invoked from a host environment like C/C++ Java or any

    other programming languages.

    11) Difference between temporary table & pl/sql table?

    12) How to write row level, statement level & instead of triggers and how should these be used?

    ANS: New and Old Qualifiers can be used with row level triggers.

    By default the trigger is always a statement level trigger.

    When we have a need of checking the requirement at each row then we should use row

    level trigger else it will check for the first row only.

    instead of triggers triggers must always fire for each row.

    13) Concept of mutating table:

    Create or replace Trigger Emp_Count

    After delete on Emp_tab

    For Each Row

    ..

    Begin

    Select Count(*) Into n From Emp tab.

    ..

    End;

  • 7/28/2019 Oracle related Questions

    9/33

    Interview questions

    1) Why Create or Replace and not Drop and recreate procedures?Ans) So that Grants are not dropped.

    2) What is the significance of & and && in pl sqlAns) & prompts for a value at runtime from the user.

    && specifies that the same value be taken for the respective variable as previously put byuser.

    3) How many rows will the following dtatememt return select * from emp whererownum=10;

    Ans ) No rows.Reason

    ROWNUM is a pseudocolumn (not a real column) that is available in a query. ROWNUM will

    be assigned the numbers 1, 2, 3, 4, ... N, where Nis the number of rows in the set ROWNUM is

    used with. A ROWNUM value is not assigned permanently to a row (this is a common

    misconception). A row in a table does not have a number; you cannot ask for row 5 from a table

    there is no such thing.

    Also confusing to many people is when a ROWNUM value is actually assigned. A ROWNUM

    value is assigned to a row after it passes the predicate phase of the query but before the query

    does any sorting or aggregation. Also, a ROWNUM value is incremented only after it is assigned,

    which is why the following query will never return a row:

    select *from t

    where ROWNUM > 1;

    Because ROWNUM > 1 is not true for the first row, ROWNUM does not advance to 2. Hence,

    no ROWNUM value ever gets to be greater than 1. Consider a query with this structure:

    select ..., ROWNUMfrom t

    where group by

    having order by ;

    Think of it as being processed in this order:

    1. The FROM/WHERE clause goes first.

    2. ROWNUM is assigned and incremented to each output row from the FROM/WHERE clause.

  • 7/28/2019 Oracle related Questions

    10/33

    3. SELECT is applied.

    4. GROUP BY is applied.

    5. HAVING is applied.

    6. ORDER BY is applied.

    That is why a query in the following form is almost certainly an error:

    select *from emp

    where ROWNUM

  • 7/28/2019 Oracle related Questions

    11/33

    Row chaining occurs when a row can no longer fit into its original block.If the entire row can fit in a new block, the row is moved completely, leaving only forwardingPointer. This is known as row migration. If the row has grown so large that it may not fit ina single block then the row is split into two or more blocks . row chaining. When Oracle isforced to split a row into pieces, it often splits individual columns into one or more pieces.Some conditions that will cause row chaining are:

    Tables whose rowsize exceeds the blocksize.Tables with long and long raw columns are prone to having chained rows.Tables with more then 255 columns will have chained rows as Oracle break wide tables up intopieces.So instead of just having a forwarding address on one block and the data on another we havedata on two or more blocks.

    8) To display the all employee name with end of S without using like operator?Ans) Select first_name from employees where substr(first_name,-1)='s';

    9) What is an explain plan and how would you go about generating it?Ans) Use the EXPLAINPLAN statement to determine the execution plan Oracle Database follows

    to execute a specified SQL statement. This statement inserts a row describing each step of theexecution plan into a specified table.

    The definition of a sample output table PLAN_TABLE is available in a SQL script on yourdistribution media. Your output table must have the same column names and datatypes as thistable. The common name of this script is UTLXPLAN.SQL. The exact name and location dependon your operating system.

    EXPLAIN PLANSET STATEMENT_ID = 'Raise in Tokyo'INTO plan_tableFOR UPDATE employees

    SET salary = salary * 1.10

    WHERE department_id =(SELECT department_id FROM departments

    WHERE location_id = 1200);

    10) explain decode function in oracleAns) DECODE function compares one expression to one or more other expressions and, whenthe base expression is equal to a search expression, it returns the corresponding resultexpression; or, when no match is found, returns the default expression when it is specified, or NAwhen it is not.SELECT employee_name, decode (employee_id, 10000, tom, 10001, peter, 10002, jack'Gateway') result FROM employee;

    11) 1 where we can find block corruption? Which view desc block corruption?

    V$backup_corruption view there to find out corrupted blocks.

    first run the following rman command

    RMAN> backup validate check logical database;RMAN does not physically backup the database with this commandbut it reads all blocks and checks for corruptions.If it finds corrupted blocks it will place the information about the corruption into a view:

  • 7/28/2019 Oracle related Questions

    12/33

    v$database_block_corruption;

    Now we can tell RMAN to recover all the blockswhich it has found as being corrupt:

    RMAN> blockrecover corruption list;# (all blocks from v$database_block_corruption)

    12) What does DBMS_pipe command do

    dbms_pipe is a IPC methodology which allows processes to communicate with each other usingpipes.

    The important functions/procedures in this package are

    (1) CREATE_PIPE to create a new pipe==> dbms_pipe.create_pipe(pipename) where pipename can be Oracle supplied or user definedas below

    dbms_pipe.create_pipe(dbms_pipe.unique_session_name) -- Creates a PIPE based on yourunique Session ID

    or

    pipename constant varchar2(100) := 'TEST_PIPE';dbms_pipe.create_pipe(pipename);

    (2) Having created the pipes try sending some data through the pipe. To send data prepare thedata using dbms_pipe.pack_message(mesg_buf) where mesg_buf can be varchar2, char,number. Basically this procedure is overloaded for Numbers, Varchar2 and date. For long andraw data use the corresponding DBMS_PIPE.PACK_MESSAGE_RAW method. This procedurebasically places the data into buffer which can be send on any pipe using thedbms_pipe.send_message(pipename) function.

    (3) At the other end of the pipe you can receive the data using dbms_pipe.receive_messagefunction. This functions fetches the data into buffer from where you can unpack the data usingdbms_pipe.unpack_message function. This function gets the data in the buffer into a messagebuffer.

    These are the basic commands that you can use for working with pipes. For more details visitoracle documentation.

    13) What is Restricted Mode of Instance Startup?Ans) An instance can be started in (or later altered to be in) restricted mode so that when thedatabase is open connections are limited only to those whose user accounts have been grantedthe RESTRICTED SESSION system privilege.

    14) You have just had to restore from backup and do not have any control files. How would yougo about bringing up this database?

    Ans) I would create a text based backup control file, stipulating where on disk all the data fileswhere and then issue the recover command with the using backup control file clause.

    Alter database backup controlfile to trace;

  • 7/28/2019 Oracle related Questions

    13/33

    15) How would you go about increasing the buffer cache hit ratio?Use the buffer cache advisory over a given workload and then query thev$db_cache_advice table. If a change was necessary then I would use the alter systemset db_cache_size command.

    16) Can one use dynamic SQL within PL/SQL? OR Can you use a DDL in aprocedure ? How ?

    Ans ) From PL/SQL V2.1 one can use the DBMS_SQL package to execute dynamic SQLstatements.Eg: CREATE OR REPLACE PROCEDURE DYNSQL AScur integer;rc integer;BEGINcur := DBMS_SQL.OPEN_CURSOR;DBMS_SQL.PARSE(cur,'CREATE TABLE X (Y DATE)', DBMS_SQL.NATIVE);rc := DBMS_SQL.EXECUTE(cur);

    DBMS_SQL.CLOSE_CURSOR(cur);END;

    1. Other way to replace query result null value with a text

    SQL> Set NULL N/Ato reset SQL> Set NULL

    2. Change SQL prompt nameSQL> set sqlprompt Manimara >

    Manimara >Manimara >

    3. How to get DDL of any object ?

    Use the describe command or use the dbms_metadata.get_ddl package.

    SELECT DBMS_METADATA.GET_DDL('TABLE','EMP') FROM dual;

    4. Display the number value in WordsSQL> select sal, (to_char(to_date(sal,'j'), 'jsp'))

    from emp;the output like,

    SAL (TO_CHAR(TO_DATE(SAL,'J'),'JSP'))--------- -----------------------------------------------------

    800 eight hundred1600 one thousand six hundred1250 one thousand two hundred fifty

    If you want to add some text like,Rs. Three Thousand only.SQL> select sal "Salary ",(' Rs. '|| (to_char(to_date(sal,'j'), 'Jsp'))|| ' only.'))"Sal in Words" from emp

    /Salary Sal in Words------- ------------------------------------------------------

    800 Rs. Eight Hundred only.

  • 7/28/2019 Oracle related Questions

    14/33

    1600 Rs. One Thousand Six Hundred only.1250 Rs. One Thousand Two Hundred Fifty only.

    In a TO_CHAR or TO_DATE functions the format mask elements are sometimes combined into asingle value. Your example converts a Julian date value into a date with the inner TO_DATEnested function and then converts that date value into the word representation of the julian date

    value with the outer TO_CHAR function.

    'J' is the Julian value stored in the database.'SP' tells the function to spell a numeric value out in words. This is case sensitive.

    'JSP' as a combined element is the Julian numeric value spelled out in words, in all caps.

    This can also be used for any numeric value such as the numeric day of the month:

    'DDSP' - the numeric date of the month spelled in words, in all caps.or'Ddspth' - the numeric date of the month spelled in words with an ordinal ending, in mixed case orinitcaps.

    5. How will you delete duplicating rows from a base table

    DELETE FROM table_name A WHERE rowid>(SELECT min(rowid) from table_name B whereB.table_no=A.table_no);CREATE TABLE new_table AS SELECT DISTINCT * FROM old_table;DROP old_table RENAME new_table TO old_table DELETE FROM table_name A WHERE rowidNOT IN (SELECT MAX(ROWID) FROM table_name GROUP BY column_name)

    6. Is there a limit on the size of a PL/SQL block?

    Answer: Currently, the maximum parsed/compiled size of a PL/SQL block is 64K and the

    maximum code size is 100K.You can run the following select statement to query the size of anexisting package or procedure.

    SQL> select * from dba_object_size where name = 'procedure_name'

    7. How can I protect my PL/SQL source code?

    Answer: PL/SQL V2.2, available with Oracle7.2, implements a binary wrapper for PL/SQLprograms to protect the source code.

    Oracle provides a way to hide code with the PL/SQL Wrapper utility. When source code has beenwrapped, not only is the file unreadable, but also when it is loaded into the database, the code

    cannot be read in the data dictionary.

    The wrapper utility does not encrypt the code. Instead, it converts it to hexadecimal digits so thatit cannot be read or edited. To run the utility, use the following syntax:wrap iname=input_file.sql oname=output_file.plb

    This way you can distribute software without having to worry about exposing your proprietaryalgorithms and methodsEven though the code is unreadable, it compiles without error.8. Can one read/write files from PL/SQL?

  • 7/28/2019 Oracle related Questions

    15/33

    Answer: Included in Oracle 7.3 is a UTL_FILE package that can read and write files.The directoryyou intend writing to has to be in your INIT.ORA file.Before Oracle 7.3 the only means of writing a file was to use DBMS_OUTPUT with the SQL*PlusSPOOL command.

    DECLARE

    fileHandler UTL_FILE.FILE_TYPE;

    BEGIN

    fileHandler := UTL_FILE.FOPEN('/home/oracle/tmp', 'myoutput', 'W');

    UTL_FILE.PUTF(fileHandler, 'Value of func1 is %s\n', func1(1));

    UTL_FILE.FCLOSE(fileHandler);

    END;

    9. To view installed Oracle version informationSQL> select banner from v$version;

    10. How will you run DOS commands in SQL prompt?Ans : In Unix: !

    In Win : $

  • 7/28/2019 Oracle related Questions

    16/33

    3. Other way to replace query result null value with a textSQL> Set NULL N/A

    to reset SQL> Set NULL

    4. Change SQL prompt nameSQL> set sqlprompt Manimara >

    Manimara >Manimara >

    3. How to get DDL of any object ?

    Use the describe command or use the dbms_metadata.get_ddl package.

    SELECT DBMS_METADATA.GET_DDL('TABLE','EMP') FROM dual;

    4. Display the number value in WordsSQL> select sal, (to_char(to_date(sal,'j'), 'jsp'))

    from emp;the output like,

    SAL (TO_CHAR(TO_DATE(SAL,'J'),'JSP'))--------- -----------------------------------------------------

    800 eight hundred1600 one thousand six hundred1250 one thousand two hundred fifty

    If you want to add some text like,Rs. Three Thousand only.SQL> select sal "Salary ",(' Rs. '|| (to_char(to_date(sal,'j'), 'Jsp'))|| ' only.'))"Sal in Words" from emp

    /Salary Sal in Words------- ------------------------------------------------------

    800 Rs. Eight Hundred only.1600 Rs. One Thousand Six Hundred only.1250 Rs. One Thousand Two Hundred Fifty only.

    In a TO_CHAR or TO_DATE functions the format mask elements are sometimes combined into asingle value. Your example converts a Julian date value into a date with the inner TO_DATEnested function and then converts that date value into the word representation of the julian datevalue with the outer TO_CHAR function.

    'J' is the Julian value stored in the database.

    'SP' tells the function to spell a numeric value out in words. This is case sensitive.

    'JSP' as a combined element is the Julian numeric value spelled out in words, in all caps.This can also be used for any numeric value such as the numeric day of the month:

    'DDSP' - the numeric date of the month spelled in words, in all caps.or'Ddspth' - the numeric date of the month spelled in words with an ordinal ending, in mixed case orinitcaps.

  • 7/28/2019 Oracle related Questions

    17/33

    5. How will you delete duplicating rows from a base table

    DELETE FROM table_name A WHERE rowid>(SELECT min(rowid) from table_name B whereB.table_no=A.table_no);CREATE TABLE new_table AS SELECT DISTINCT * FROM old_table;DROP old_table RENAME new_table TO old_table DELETE FROM table_name A WHERE rowid

    NOT IN (SELECT MAX(ROWID) FROM table_name GROUP BY column_name)

    10. Is there a limit on the size of a PL/SQL block?

    Answer: Currently, the maximum parsed/compiled size of a PL/SQL block is 64K and themaximum code size is 100K.You can run the following select statement to query the size of anexisting package or procedure.

    SQL> select * from dba_object_size where name = 'procedure_name'

    11. How can I protect my PL/SQL source code?

    Answer: PL/SQL V2.2, available with Oracle7.2, implements a binary wrapper for PL/SQLprograms to protect the source code.

    Oracle provides a way to hide code with the PL/SQL Wrapper utility. When source code has beenwrapped, not only is the file unreadable, but also when it is loaded into the database, the codecannot be read in the data dictionary.

    The wrapper utility does not encrypt the code. Instead, it converts it to hexadecimal digits so thatit cannot be read or edited. To run the utility, use the following syntax:wrap iname=input_file.sql oname=output_file.plb

    This way you can distribute software without having to worry about exposing your proprietaryalgorithms and methodsEven though the code is unreadable, it compiles without error.12. Can one read/write files from PL/SQL?

    Answer: Included in Oracle 7.3 is a UTL_FILE package that can read and write files.The directoryyou intend writing to has to be in your INIT.ORA file.Before Oracle 7.3 the only means of writing a file was to use DBMS_OUTPUT with the SQL*PlusSPOOL command.

    DECLARE

    fileHandler UTL_FILE.FILE_TYPE;

    BEGIN

    fileHandler := UTL_FILE.FOPEN('/home/oracle/tmp', 'myoutput', 'W');

    UTL_FILE.PUTF(fileHandler, 'Value of func1 is %s\n', func1(1));

    UTL_FILE.FCLOSE(fileHandler);

    END;

  • 7/28/2019 Oracle related Questions

    18/33

    13. To view installed Oracle version informationSQL> select banner from v$version;

    10. How will you run DOS commands in SQL prompt?Ans : In Unix: !

    In Win : $

    1. Describe the difference between a procedure, function and anonymous pl/sql block.

    Candidate should mention use of DECLARE statement, a function must return a value while aprocedure doesn't have to.

    2. What is a mutating table error and how can you get around it?

    This happens with triggers. It occurs because the trigger is trying to update a row it is currentlyusing. The usual fix involves either use of views or temporary tables so the database is selectingfrom one while updating the other.

    3. Describe the use of %ROWTYPE and %TYPE in PL/SQL

    %ROWTYPE allows you to associate a variable with an entire table row.The %TYPE associates a variable with a single column type.

    4. What packages (if any) has Oracle provided for use by developers?

    Oracle provides the DBMS_ series of packages. There are manywhich developers should be aware of such as DBMS_SQL, DBMS_PIPE,DBMS_TRANSACTION,DBMS_LOCK, DBMS_ALERT, DBMS_OUTPUT, DBMS_JOB, DBMS_UTILITY, DBMS_DDL,UTL_FILE. If they can mention a few of these and describe how they used them, even better.

    If they include the SQL routines provided by Oracle, great, but not really what was asked.

    5. Describe the use of PL/SQL tablesPL/SQL tables are scalar arrays that can be referenced by a

    binary integer. They can be used to hold values for use in later queriesor calculations. In Oracle 8 they will be able to be of the %ROWTYPE designation, or RECORD.

    6. When is a declare statement needed ?The DECLARE statement is used in PL/SQL anonymous blocks such as with stand alone, non-

    stored PL/SQL procedures. It must come first in a PL/SQL stand alone file if it is used.

    7. In what order should a open/fetch/loop set of commands in a PL/SQL block be implemented ifyou use the NOTFOUND cursor variable in the exit when statement? Why?OPEN then FETCH then LOOP followed by the exit when. If not specified in this order will result

    in the final return being done twice because of the way the %NOTFOUND is handled by PL/SQL.

    8. What are SQLCODE and SQLERRM and why are they important for PL/SQL developers?Expected answer: 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

  • 7/28/2019 Oracle related Questions

    19/33

    used in exception handling to report, or, store in an error log table, the error that occurred in thecode. These are especially useful for the WHEN OTHERS exception.

    9. How can you find within a PL/SQL block, if a cursor is open?

    Expected answer: Use the %ISOPEN cursor status variable.

    10. How can you generate debugging output from PL/SQL?

    Expected answer: Use the DBMS_OUTPUT package. Another possible method is to just use theSHOW ERROR command, but this only shows errors. The DBMS_OUTPUT package can beused to show intermediate results from loops and the status of variables as the procedure isexecuted. The new package UTL_FILE canalso be used.

    11. What are the types of triggers?

    Expected Answer: There are 12 types of triggers in PL/SQL that consist ofcombinations of the BEFORE, AFTER, ROW, TABLE, INSERT, UPDATE, DELETE and

    ALL key words:

    BEFORE ALL ROW INSERTAFTER ALL ROW INSERTBEFORE INSERT

    AFTER INSERT etc.

    12.What's Mutating Table

    Mutating Table is a table that is currently being modified by an Insert, Update or Deletestatement. Constraining Table is a table that a triggering statement might need to read eitherdirectly for a SQL statement or indirectly for a declarative Referential Integrity constraints. PseudoColumns behaves like a column in a table but are not actually stored in the table. E.g. Currval,Nextval, Rowid, Rownum, Level etc

    13.What's Correlated Subquery

    Correlated Subquery is a subquery that is evaluated once for each row processed by the parentstatement. Parent statement can be Select, Update or Delete. Use CRSQ to answer multipartquestions whose answer depends on the value in each row processed by parent statement.

    14.Which command displays the SQL command in the SQL buffer, and then executes it?

    RUN.

    15.Under which circumstance must you recompile the package body after recompiling thepackage specification?

    Altering the argument list of one of the package constructs Any change made to one of the package constructs

    Any SQL statement change made to one of the package constructs

    Removing a local variable from the DECLARE section of one of the package constructs

    16.What does teh term upsizing refer to ?

  • 7/28/2019 Oracle related Questions

    20/33

    Applications that have outgrown their environment are re-engineered to run in a largerenvironment. This is upsizing.

    17.What is a database link?

    Database link is a named path through which a remote database can be accessed

    18.How you will avoid your query from using indexes?

    SELECT * FROM empWhere emp_no+' '=12345;

    i.e you have to concatenate the column name with space within codes in the wherecondition.SELECT /*+ FULL(a) */ ename, emp_no from emp

    where emp_no=1234;

    i.e using HINTS

    19. What is the difference between NO DATA FOUND and %NOTFOUND ?

    NO_DATA_FOUND is system defined exception. This is generated when no rows selected.

    NOTFOUND is attribute which is used with cursor. If cursor returns no row then NOTFOUNDreturns true and if returns row then NOTFOUND is false.

    20.Which is more faster - IN or EXISTS?

    EXISTS is more faster than IN because EXISTS returns a Boolean value whereas IN returns avalue

    1-->What is the fastest way of accessing a row in a table--------------------------------------------------------------------------------Quote

    A ROWID is created by Oracle for each new row in every table it is a pseudo column that has avalue forevery row in a table. The ROWID gives us the physical address of a row and is the fastest way toaccess any row.

    The ROWID contains 3 bits of information they are :-

    The block within the database file.Row # within the block.Database file ID.

    An example could be :-

    000088C9.0191.0002The ROWID has three important uses it is :-

  • 7/28/2019 Oracle related Questions

    21/33

    The fastest path to any row.A way of speeding the COMMIT process in application code.Unique identifiers of any given row.

    2-->How many LONG columns are allowed in a table--------------------------------------------------------------------------------Only one column can have LONG data type. And that column cannot be used in WHERE clauseor in ORDER BY clause.

    Also we cannot add primary key constraint to that column only not to the whole table that meanswe will give primarykey to any column in the table except the column having the long data type. If we give we get the

    error ORA-02269: keycolumn cannot be of LONG datatype.

    3--> What is Bitmapped indexes?2. What is b-tr...--------------------------------------------------------------------------------Conventional wisdom holds that bitmap indexes are most appropriate for columns having lowdistinct values such as

    GENDER MARITAL_STATUS and RELATION. This assumption is not completely accuratehowever. In reality a bitmap index isalways advisable for systems in which data is not frequently updated by many concurrent

    systems. In fact as I'll demonstratehere a bitmap index on a column with 100-percent unique values (a column candidate for primarykey) is as efficient as a B-tree index.

    There are several disadvantages to using a bitmap index on a unique column one being the needfor sufficient space(and Oracle does not recommend it). However the size of the bitmap index depends on the

    cardinality of the column onwhich it is created as well as the data distribution. Consequently a bitmap index on the GENDERcolumn will be smaller

    than a B-tree index on the same column. In contrast a bitmap index on EMPNO (a candidate forprimary key) will be muchlarger than a B-tree index on this column. But because fewer users access decision-support

    systems (DSS) systems than wouldaccess transaction-processing (OLTP) ones resources are not a problem for these applications

    4--> What is the difference between cold backup and hot...--------------------------------------------------------------------------------Cold Backup- We can take the Backup while DB(eg. Oracle) is down.Hot Backup-We can take the Backup while DB(eg. Oracle) is running.

    Cold backup is a physical backup. During a cold backup the database is closed and not available

    to users. All files ofthe database are copied (image copy). The datafiles do not change during the copy so thedatabase is in sync upon restore.Used when:Service level allows for some down time for backupHot backup is a physical backup. In a hot backup the database remains open and available tousers. All files of the database arecopied (image copy). There may be changes to the database as the copy is made and so all log

    files of changes being made duringthe backup must be saved too. Upon a restore the changes in the log files are reapplied to bringthe database in sync. Used when:

  • 7/28/2019 Oracle related Questions

    22/33

    A full backup of a database is neededService level allows no down time for the backup

    5-->What is the different between Stand Alone Procedure and Package?Procedure is a named PL/SQL block tht is stored in the database.Package is a collection of functions and procedures stored within the database.Pkg consists of 2 parts1. Specification - declares types,functions,procedures,exceptions,cursors2. Body - implements the specificationWhenevr a func/proc is referenced from the pkg thn the entire pkg is loaded in the memory so thtwhn a diff func from the samepkg is referenced thn its already there in the memory

    6-->can we insert a record in dual?

    Dual is a table owned by sys user and public synonym for the same is created.So it is available to all the users of the database.

    To get the details use following query :

    select * from all_synonyms awhere a.synonym_name = 'DUAL';

    By using create table to create dual table we can insert into dual .

    But without creating dual we cannot insert into dual.As we didn't have insert object privilege onsys.dual table or public synonym dual.

    CREATE TABLE DUAL(COL1 VARCHAR(1));select sysdate from dualinsert into dual values('X')commitinsert into dual values('X')

    7-->How and in what way REPLACE is different from TRANSLATE?

    Translate:

    It is used to replace charecter by charecter

    Ex:

    Select translate('ashok','xp','sk')from dual;result: ashok

    Replace:

    It is used to replace word by word

    Ex:select replace('tech world','Tech','technology')from dual;

  • 7/28/2019 Oracle related Questions

    23/33

    result: technology world

    8-->How do you view the last record added to a table?

    select * from emp where rowid = ( select max(rowid) from emp);

    9-->what is a reverse key index and it's real time us...--------------------------------------------------------------------------------Reverse -key index is index that reverse the data of the being indexed column. For example if thecolumn value contains LOVELYthe reverse-key index will be YLEVOL.

    This index very much useful where users issues the select command with where clause such asWHERE x 5 but it will not be useful for searchingin range say WHERE x between 2 and 6.12Reverse key index optimises the Oracle performance in real application cluster environment

    To change an existing index as a reverse key index you can use the alter index statement.

    alter index indexname rebuild reverse;

    10-->In Oracle10g sqlplus, how do you find the tables that have been dropped?

    When you drop a table normally the database does not immediately release the space associatedwith the table.Rather the database renames the table and places it in a recycle bin where it can later be

    recovered with the FLASHBACK TABLE statementif you find that you dropped the table in error.

    select * from recyclebin;

    using this query we can see the tables which are dropped

    FLASHBACK TABLE emp11 TO BEFORE DROP;

    11--> What is a rank function?

    In Oracle/PLSQL, the rank function returns the rank of a value in a group of values. It is verysimilar to the dense_rank function.However, the rank function can cause non-consecutive rankings if the tested values are thesame. Whereas, the dense_rank function will

    always result in consecutive rankings.

    The rank function can be used two ways - as an Aggregate function or as an Analytic function.

    Aggregate functionselect rank(1000, 500) WITHIN GROUP (ORDER BY salary, bonus)from employees;

    The SQL statement above would return the rank of an employee with a salary of $1,000 and abonus of $500 from within the employees table.

  • 7/28/2019 Oracle related Questions

    24/33

    Analytic functionselect employee_name, salary,rank() OVER (PARTITION BY department ORDER BY salary)from employeeswhere department = 'Marketing';

    The SQL statement above would return all employees who work in the Marketing department andthen calculate a rank foreach unique salary in the Marketing department. If two employees had the same salary, the rankfunction would return the samerank for both employees. However, this will cause a gap in the ranks (ie: non-consecutive ranks).This is quite different from thedense_rank function which generates consecutive rankings.

    12-->What is partitioning ?Partitioning can provide tremendous benefits to a wide variety of applications by improvingmanageability, performance, and availability.

    It is not unusual for partitioning to improve the performance of certain queries or maintenanceoperations by an order of magnitude. Moreover,partitioning can greatly simplify common administration tasks.

    Partitioning also enables database designer and administrators to tackle some of the toughestproblems posed by cutting-edge applications.Partitioning is a key tool for building multi-terabyte systems or systems with extremely highavailability requirements.

    Basics of PartitioningPartitioning allows a table, index or index-organized table to be subdivided into smaller pieces.Each piece of database object is called apartition. Each partition has its own name, and may optionally have its own storage

    characteristics, such as having table compression enabledor being stored in different tablespaces. From the perspective of a database administrator, a

    partitioned object has multiple pieces which canbe managed either collectively or individually. This gives the administrator considerably flexibilityin managing partitioned objects. However,from the perspective of the application, a partitioned table is identical to a non-partitioned table;

    no modifications are necessary when accessinga partitioned table using SQL DML commands.

    Tables are partitioned using a 'partitioning key', a set of columns which determine in whichpartition a given row will reside. Oracle9i provides fivetechniques for partitioning tables:

    Range Partitioning: Each partition is specified by a range of values of the partitioning key (for atable with a date column as the partitioning key, the 'January-2001' partition contains rows with the partitioning-key values from '01-JAN-2001' -'31-JAN-2001')List Partitioning: Each partition is specified by a list of values of the partitioning key (for a tablewith a region column as the partitioning key,the 'North America' partition may contain values 'Canada', 'USA', and 'Mexico')

    Hash Partitioning: A hash algorithm is applied to the partitioning key to determine the partition fora given row

  • 7/28/2019 Oracle related Questions

    25/33

    Composite Range-Hash Partitioning: A combination of the Range and Hash partitioningtechnique. The table is first range-partitioned, and then eachindividual range-partition is further sub-partitioned using the hash partitioning technique. All sub-

    partitions for a given range partition togetherrepresent a logical subset of the data.

    Composite Range-List Partitioning: A combination of the Range and List partitioning technique.The table is first range-partitioned, and then eachindividual range-partition is further sub-partitioned using a list partitioning technique. Unlikecomposite Range-Hash partitioning, the content ofeach sub-partition represents a logical subset of the data, described by its appropriate Range andList partition setup.

    Difference between implicit and explicit cursors

    1. imlicit cursors are faster2. implicit cursors includes a NO_DATA_FOUND and a TOO_MANY_ROWS exception

    check.

    CREATE OR REPLACE PROCEDURE cursor_comparison ASl_loops number := 10000 ;l_dummy dual.dummy%TYPE ;l_start NUMBER ;

    CURSOR c_dual IS SELECT dummy FROM dual ;

    BEGIN---- Time explicit cursor.

    L_start := DBMS_UTILITY.get_time ;

    FOR I IN 1 .. l_loops LOOPOPEN c_dual ;FETCH c_dual INTO l_dummy ;CLOSE c_dual ;

    END LOOP ;

    DBMS_OUTPUT.PUT_LINE(Explicit: ||DBMS_UTILITY.get_time l_start)) ;

    ----Time implicit cursor

    L_start := DBMS_UTILITY.get_time ;

    FOR I IN 1 .. l_loops LOOP

    SELECT dummy INTO l_dummy FROM dual ;END LOOP ;

    DBMS_OUTPUT.PUT_LINE(Implicit: ||DBMS_UTILITY.get_time l_start)) ;

    END cursor_comparison ;

    /SHOW ERRORS

  • 7/28/2019 Oracle related Questions

    26/33

    SET SERVEROUTPUT ONEXEC cursor_comparison ;Explicit : 203Implicit : 162

    The volume of code being used . PL/SQL is an interpreted language so every extra line of codeadds to the total processing time. As a rule of thumb, make the code as compact as possiblewithout making it unsupportable.

    Some other key differences between PL/SQL(Index-by Tables) and Nested Tables:

    To extend a Nested table, you need to use a built-in procedure EXTEND, but to extend a PL/SQLtable, you just increment the subscripts.

    The value of an uninitialized Nested table is NULL, but an uninitialized PL/SQL table is empty.So, you can compare nested tables using IS NULL operator.

    PL/SQL tables are initially sparse. They can store reference data using a numeric primary

    key as the index.

    PL/SQL supports implicit (automatic) datatype conversion between Arrays and PL/SQLtables.

    explain plan

    Whenever you read or write data in Oracle, you do so by issuing anSQL statement. One ofOracle's task when it receives such a statement is to build a query execution plan. An executionplan defines how Oracle finds or writes the data. For example, an important decision that Oraclehas to take is if it uses indexes or not. And if there are more indexes, which of these is used. Allthis is contained in an execution plan.If one wants to explore such an execution plan, Oracle provides the SQL statement EXPLAINPLAN to determine this.The general syntax of EXPLAIN PLAN is:

    explain plan forsql-statement;

    explain plan set statement_id='some identifier' forsql-statement;

    explain plan set statement_id='some identifier' into table_name forsql-statement;explain plan into table_name forsql-statement;

    If you do an EXPLAIN PLAN, Oracle will analyze the statment and fill a special table with theExecution plan for that statement. You can indicate which table has to be filled with the followingSQL command:

    explain planinto table_name for your-precious-sql-statement;

    If you omit the INTO TABLE_NAME clause, Oracle fills a table named PLAN_TABLE by default.

    http://www.adp-gmbh.ch/ora/concepts/sql_stmt.htmlhttp://www.adp-gmbh.ch/ora/concepts/sql_stmt.htmlhttp://www.adp-gmbh.ch/ora/concepts/sql_stmt.htmlhttp://www.adp-gmbh.ch/ora/sql/execution_plan.htmlhttp://www.adp-gmbh.ch/ora/sql/execution_plan.htmlhttp://www.adp-gmbh.ch/ora/sql/explain_plan.htmlhttp://www.adp-gmbh.ch/ora/sql/explain_plan.htmlhttp://www.adp-gmbh.ch/ora/concepts/sql_stmt.htmlhttp://www.adp-gmbh.ch/ora/sql/execution_plan.htmlhttp://www.adp-gmbh.ch/ora/sql/explain_plan.html
  • 7/28/2019 Oracle related Questions

    27/33

    The Plan Table

    The plan table is the table that Oracle fills when you have it explain an execution plan for an SQLstatement. You must make sure such a plan table exists. Oracle ships with the scriptUTLXPLAN.SQL which creates this table, named PLAN_TABLE (which is the default name usedby EXPLAIN PLAN). If you like, however, you can choose any other name for the plan table, aslong as you have been granted insert on it and it has all the fields as here.

    The fields (attributes) within the plan table

    Arguably, the most important fields within the plan table are operation, option, object_name, id,andparent_id. The pair operation and object_name define what operation would be done on (orwith) object_name. If an operation has an id which other operations have as parent_id, it meansthe other operations feed their result to the parent.Possible values for operation are:

    DELETE STATEMENT

    INSERT STATEMENT

    SELECT STATEMENT

    UPDATE STATEMENT

    AND-EQUAL

    CONNECT BY

    CONCATENATION

    COUNT

    DOMAIN INDEX

    FILTER

    FIRST ROW

    FOR UPDATE

    HASH JOIN

    INDEX

    INLIST ITERATOR

    INTERSECTION

    MERGE JOIN MINUS

    NESTED LOOPS

    PARTITION,

    REMOTE

    SEQUENCE

    SORT

    TABLE ACCESS

    UNION

    VIEW

    Option tells more about how an operation would be done. For example, the operation TABLEACCESS can have the options: FULL or BY ROWID or many others. Full in this case means, thatthe entire table is accessed (takes a long time if table is huge) whereas BY ROWID means,Oracle knows where (from which block) the rows are to be retrieved, which makes the time toaccess the table shorter.

    dbms_xplan

    As of 9i, dbms_xplan can be used to format the plan table.

    SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);

    http://www.adp-gmbh.ch/ora/exp_plan/plan_table.htmlhttp://www.adp-gmbh.ch/ora/sql/join/join_methods.html#merge_joinhttp://www.adp-gmbh.ch/ora/sql/join/join_methods.html#nested_loopshttp://www.adp-gmbh.ch/ora/plsql/dbms_xplan.htmlhttp://www.adp-gmbh.ch/ora/exp_plan/plan_table.htmlhttp://www.adp-gmbh.ch/ora/sql/join/join_methods.html#merge_joinhttp://www.adp-gmbh.ch/ora/sql/join/join_methods.html#nested_loopshttp://www.adp-gmbh.ch/ora/plsql/dbms_xplan.html
  • 7/28/2019 Oracle related Questions

    28/33

    Example 9-4 Using EXPLAIN PLAN with the INTO Clause

    EXPLAIN PLAN INTO my_plan_tableFOR SELECT last_name FROM employees;

    AUTOTRACE - The Easy Option?

    Switching on the AUTOTRACE parameter in SQL*Plus causes an explain to be performed onevery query.SQL> SET AUTOTRACE ONSQL> SELECT * FROM emp e, dept d

    WHERE e.deptno = d.deptno AND e.ename = 'SMITH';EMPNO ENAME JOB MGR HIREDATE SAL COMM

    ---------- ---------- --------- ---------- --------- ---------- ----------DEPTNO DEPTNO DNAME LOC

    ---------- ---------- -------------- -------------7369 SMITH CLERK 7902 17-DEC-80 800

    20 20 RESEARCH DALLAS

    Execution Plan----------------------------------------------------------

    0 SELECT STATEMENT Optimizer=CHOOSE1 0 NESTED LOOPS2 1 TABLE ACCESS (FULL) OF 'EMP'3 1 TABLE ACCESS (BY INDEX ROWID) OF 'DEPT'4 3 INDEX (UNIQUE SCAN) OF 'PK_DEPT' (UNIQUE)

    Statistics----------------------------------------------------------81 recursive calls4 db block gets27 consistent gets0 physical reads0 redo size

    941 bytes sent via SQL*Net to client425 bytes received via SQL*Net from client2 SQL*Net roundtrips to/from client0 sorts (memory)0 sorts (disk)1 rows processed

    SQL>This is a relatively easy way to get the execution plan but there is an issue. In order to get theexecution plan the statement must be run to completion. If the query is particularly inefficientand/or returns many rows, this may take a considerable time. At first glance, using theTRACEONLY option ofAUTOTRACE seems to remove this issue, but this option merely supressesthe output of the query data, it doesn't prevent the statement being run. As such, long runningqueries will still take a long time to complete, but they will not present their data. The followingexample show this in practice.

  • 7/28/2019 Oracle related Questions

    29/33

    The query takes the same time to return (about 10seconds) whether the TRACEONLY option is used or not. If theTRACEONLY option prevented the query running, you would expect itto return instantly, like an EXPLAIN PLAN.

    EXPLAIN PLANThe EXPLAIN PLAN method doesn't require thequery to be run, greatly reducing the time it takes to get an execution plan forlong-running queries compared to AUTOTRACE. First the query must beexplained:

    SQL> EXPLAIN PLAN FOR2 SELECT *3 FROM emp e, dept d4 WHERE e.deptno = d.deptno5 AND e.ename = 'SMITH';

    Explained.SQL>

    Then the execution plan displayed:

    SQL> @$ORACLE_HOME/rdbms/admin/utlxpls.sqlPlan Table--------------------------------------------------------------------------------| Operation | Name | Rows | Bytes| Cost | Pstart| Pstop |--------------------------------------------------------------------------------| SELECT STATEMENT | | | | | | || NESTED LOOPS | | | | | | || TABLE ACCESS FULL |EMP | | | | | || TABLE ACCESS BY INDEX RO|DEPT | | | | | || INDEX UNIQUE SCAN |PK_DEPT | | | | | |--------------------------------------------------------------------------------

    8 rows selected.

    SQL>For parallel queries use the utlxplp.sql scriptinstead of utlxpls.sql.

    Statement ID

    If multiple people are accessing the same plan table, oryou would like to keep a history of the execution plans you should use theSTATEMENT_ID. This associates a user specified ID with each planwhich can be used when retrieving the data.

    SQL> EXPLAIN PLAN SET STATEMENT_ID = 'TIM' FOR2 SELECT *3 FROM emp e, dept d4 WHERE e.deptno = d.deptno5 AND e.ename = 'SMITH';

    Explained.

    SQL> @explain.sql TIM

  • 7/28/2019 Oracle related Questions

    30/33

    PLAN OBJECT_NAME OBJECT_TYPE BYTES COSTPARTITION_START PARTITION_STOP-------------------------------------- --------------- --------------- ----- ----- --------------- ---------------Select Statement 57 4

    1.1 Nested Loops 57 42.1 Table Access (Full) EMP TABLE 37 32.2 Table Access (By Index Rowid) DEPT TABLE 20 1

    3.1 Index (Unique Scan) PK_DEPT INDEX (UNIQUE) 0

    5 rows selected.

    SQL>By default the Oracle scripts to not accept astatement_id parameter. You can easily modify the scripts or you can use thescript listed under DBA Scripts on this site.

    21108

    insteadof

    INSTEAD OF Triggers

    INSTEAD OF triggers provide a transparent way of modifying views that cannot be modifieddirectly through DML statements (INSERT, UPDATE, and DELETE). These triggers are calledINSTEAD OF triggers because, unlike other types of triggers, Oracle fires the trigger instead ofexecuting the triggering statement.

    You can write normal INSERT, UPDATE, and DELETE statements against the view and theINSTEADOF trigger is fired to update the underlying tables appropriately. INSTEADOF triggersare activated for each row of the view that gets modified.

    Views That Are Not Modifiable

    A view is inherently modifiable if data can be inserted, updated, or deleted without usingINSTEAD OF triggers and if it conforms to the restrictions listed as follows. If the view querycontains any of the following constructs, the view is not inherently modifiable and you thereforecannot perform inserts, updates, or deletes on the view:

    Set operators

    Aggregate functions

    GROUP BY, CONNECT BY, or START WITH clauses

    The DISTINCT operator Joins (however, some join views are updatable)

    If a view contains pseudocolumns or expressions, you can only update the view with an UPDATEstatement that does not refer to any of the pseudocolumns or expressions

    CREATE TABLE Project_tab (Prj_level NUMBER,

  • 7/28/2019 Oracle related Questions

    31/33

    Projno NUMBER,Resp_dept NUMBER);

    CREATE TABLE Emp_tab (Empno NUMBER NOT NULL,Ename VARCHAR2(10),Job VARCHAR2(9),Mgr NUMBER(4),Hiredate DATE,Sal NUMBER(7,2),Comm NUMBER(7,2),Deptno NUMBER(2) NOT NULL);

    CREATE TABLE Dept_tab (

    Deptno NUMBER(2) NOT NULL,Dname VARCHAR2(14),Loc VARCHAR2(13),Mgr_no NUMBER,Dept_type NUMBER);

    The following example shows an INSTEADOF trigger for inserting rows into the MANAGER_INFOview.

    CREATE OR REPLACE VIEW manager_info ASSELECT e.ename, e.empno, d.dept_type, d.deptno, p.prj_level,

    p.projnoFROM Emp_tab e, Dept_tab d, Project_tab pWHERE e.empno = d.mgr_noAND d.deptno = p.resp_dept;

    CREATE OR REPLACE TRIGGER manager_info_insertINSTEAD OF INSERT ON manager_infoREFERENCING NEW AS n -- new manager information

    FOR EACH ROWDECLARE

    rowcnt number;BEGIN

    SELECT COUNT(*) INTO rowcnt FROM Emp_tab WHERE empno = :n.empno;IF rowcnt = 0 THEN

    INSERT INTO Emp_tab (empno,ename) VALUES (:n.empno, :n.ename);ELSE

    UPDATE Emp_tab SET Emp_tab.ename = :n.enameWHERE Emp_tab.empno = :n.empno;

    END IF;SELECT COUNT(*) INTO rowcnt FROM Dept_tab WHERE deptno = :n.deptno;

    IF rowcnt = 0 THENINSERT INTO Dept_tab (deptno, dept_type)

    VALUES(:n.deptno, :n.dept_type);ELSE

    UPDATE Dept_tab SET Dept_tab.dept_type = :n.dept_typeWHERE Dept_tab.deptno = :n.deptno;

    END IF;SELECT COUNT(*) INTO rowcnt FROM Project_tab

    WHERE Project_tab.projno = :n.projno;

  • 7/28/2019 Oracle related Questions

    32/33

    IF rowcnt = 0 THENINSERT INTO Project_tab (projno, prj_level)

    VALUES(:n.projno, :n.prj_level);ELSE

    UPDATE Project_tab SET Project_tab.prj_level = :n.prj_levelWHERE Project_tab.projno = :n.projno;

    END IF;END;

    The actions shown for rows being inserted into the MANAGER_INFO view first test to see ifappropriate rows already exist in the base tables from which MANAGER_INFO is derived. Theactions then insert new rows or update existing rows, as appropriate. Similar triggers can specifyappropriate actions forUPDATE and DELETE.

    1. select * from recyclebincreate table yyy as select * from ACC_INSTL_PLAN_ITEMdrop table yyyflashback table yyy to before drop

    2. Display the number value in WordsSQL> select sal, (to_char(to_date(sal,'j'), 'jsp'))

    from emp;the output like,

    SAL (TO_CHAR(TO_DATE(SAL,'J'),'JSP'))--------- -----------------------------------------------------

    800 eight hundred1600 one thousand six hundred1250 one thousand two hundred fifty

    If you want to add some text like,Rs. Three Thousand only.SQL> select sal "Salary ",(' Rs. '|| (to_char(to_date(sal,'j'), 'Jsp'))|| ' only.'))"Sal in Words" from emp

    /Salary Sal in Words------- ------------------------------------------------------

    800 Rs. Eight Hundred only.1600 Rs. One Thousand Six Hundred only.1250 Rs. One Thousand Two Hundred Fifty only.

    In a TO_CHAR or TO_DATE functions the format mask elements are sometimes combined into asingle value. Your example converts a Julian date value into a date with the inner TO_DATEnested function and then converts that date value into the word representation of the julian datevalue with the outer TO_CHAR function.

    'J' is the Julian value stored in the database.'SP' tells the function to spell a numeric value out in words. This is case sensitive.'JSP' as a combined element is the Julian numeric value spelled out in words, in all caps.

  • 7/28/2019 Oracle related Questions

    33/33

    This can also be used for any numeric value such as the numeric day of the month:'DDSP' - the numeric date of the month spelled in words, in all caps.or'Ddspth' - the numeric date of the month spelled in words with an ordinal ending, in mixed case orinitcaps.

    3. How will you delete duplicating rows from a base table

    DELETE FROM table_name A WHERE rowid>(SELECT min(rowid) from table_name B whereB.table_no=A.table_no);

    CREATE TABLE new_table AS SELECT DISTINCT * FROM old_table;

    DROP old_table RENAME new_table TO old_table DELETE FROM table_name A WHERE rowidNOT IN (SELECT MAX(ROWID) FROM table_name GROUP BY column_name)