You are on page 1of 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 they take chunks of additional storage that are composed of contiguous data blocks. These groupings of 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, all you 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 they hold? 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 a reader 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. in Automatic Undo Management mode, increase the setting of UNDO_RETENTION.

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 back only 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 on July 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 timestamp or SCN Automatically restores all of the table attributes, such as indexes, triggers, and the like that 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 and so on. Some common problems with their solutions when statement fails: Access tables without appropriate privileges. Running out of space Logical errors User Process Failure- An abnormal termination of a user session. PMON checks all user processes 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 the session is disconnected from the database. To avoid this provide redundant network paths and additional listener connections. User Error Failure- An error message is not generated, but the operations result, such as dropping a table, is not what the user intended.

Instance Failure- It occurs when the instance shuts down without synchronizing all the data files to the same SCN, requiring recovery operation the next time instance is started. Causes: Power outage Hardware failure Oracle background process failure SHUTDOWN ABORT Media Failure- It is a type of failure that results in loss of one or more datafiles, control files or redo 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 and DDL 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, group numbers and states of redo log files..

11 What is the result of select * from table1, table2? Answer: The result will be the cartesian product of the rows There 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 control files and data files. CKPT (checkpoint) background process updates the SCN numbers from control files to the datafiles. SMON (system monitor) background process checks for the SCN numbers to be same in both datafiles and control files while starting the database. If same then only the database is consistent. Otherwise the database will not start.

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 user command. The syntax for changing a password is: alter user user_name identified by new_password; user_name is the user whose password you wish to change. new_password is the new password to assign. For example: If you wanted to reset the password for a user named smithj, and you wanted to set the new 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 SHARE ROW EXCLUSIVE SHARE UPDATE SHARE SHARE ROW EXCLUSIVE EXCLUSIVE. 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 segment where 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?

Answer: You can insert multiple rows using the following syntax: INSERT ALL INTO 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 ALL INTO 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 into both the suppliers and customers table, you could run the following SQL statement: INSERT ALL INTO 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<=3; Since DB version 8i, you may use order by in a view or subquery. Before you couldn't. 7) What is the difference between a sub-query and an in-line view? There is a difference between in-line views and sub-queries. In-line views can have an order by clause as of 8i. However a sub-query cannot have an order by. An example of a sub-query would be something like: SELECT * FROM emp

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 CLOSE in 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/SQL block you are working with implicit cursors. These statements include INSERT UPDATE DELETE and SELECT INTO statements. Unlike explicit cursors implicit cursors do not need 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 a result set from client and server programs. You can also use cursor variables to hide minor variations in queries. The syntax for a REF_CURSOR type is: TYPE ref_cursor_names IS REF CURSOR [RETURN record_type];

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 query at runtime. A REF CURSOR declaration with a RETURN clause defines a strong REF CURSOR. A cursor variable based on a strong REF CURSOR can be associated with queries whose result sets match the number and datatype of the record structure after the RETURN at runtime. To use cursor variables you must first create a REF_CURSOR type then declare a cursor variable 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. TYPE company_curtype IS REF CURSOR RETURN companies ROWTYPE; -- Create the variable based on the REF CURSOR. company_cur company_curtype; -- And now the weak general approach. TYPE any_curtype IS REF CURSOR; generic_curvar any_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 SQl statement at the same time and this statement is known when block is compiled. A Cursor 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 associated with 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 can be used it needs to point to a valid area of memory which can be created either by allocating it to the client-side program or on the server by PL/SQL engine. A REF CURSOR can be of Two type Strongly Typed Cursor and Weakly Typed Cursor

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?

Ans: Use the V$OPEN_CURSOR view 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;

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 sql Ans) & prompts for a value at runtime from the user. && specifies that the same value be taken for the respective variable as previously put by user. 3) How many rows will the following dtatememt return select * from emp where rownum=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 N is 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 ..., ROWNUM from t where <where clause> group by <columns> having <having clause> order by <columns>;

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.

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 <= 5 order by sal desc; 4) If I have an execute privilege on a procedure in another users schema, can I execute his procedure even though I do not have privileges on the tables within the procedure ? Ans) yes. 5) If you insert a row in a table, then create another table and then say Rollback.In this case will the row be inserted ? Ans) Yes.Because Create table is a DDL which commits automatically as soon as it is executed.The DDL commits the transaction even if the create statement fails internally (eg table already exists error) and not syntactically. 6) What is a database link Data Base Link. Use the CREATE DATABASE LINK statement to create a database link. A database link is a schema object in one database that enables you to access objects on another database. The other database need not be an Oracle Database system. However, to access non-Oracle systems you must use Oracle Heterogeneous Services. Once you have created a database link, you can use it to refer to tables and views on the other database. In SQL statements, you can refer to a table or view on the other database by appending @dblink to the table or view name. You can query a table or view on the other database with the SELECT statement. You can also access remote tables and views using any INSERT, UPDATE, DELETE, or LOCK TABLE statement. create database link <name> connected to <username> Identified by <pwd> using <string> Eg: create database link ora8idev 2 connect to scott 3 identified by tiger 4 using 'ora8idev'

7) What is a row chaining? Ans) If a row is too large to fit into a single database block row chaining happens. For example if you use a 4KB blocksize for your database and you need to insert a row of 8KB into it Oracle will use 3 blocks and store the row in pieces.

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 forwarding Pointer. This is known as row migration. If the row has grown so large that it may not fit in a single block then the row is split into two or more blocks . row chaining. When Oracle is forced 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 into pieces. So instead of just having a forwarding address on one block and the data on another we have data 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 EXPLAIN PLAN statement to determine the execution plan Oracle Database follows to execute a specified SQL statement. This statement inserts a row describing each step of the execution plan into a specified table. The definition of a sample output table PLAN_TABLE is available in a SQL script on your distribution media. Your output table must have the same column names and datatypes as this table. The common name of this script is UTLXPLAN.SQL. The exact name and location depend on your operating system. EXPLAIN PLAN SET STATEMENT_ID = 'Raise in Tokyo' INTO plan_table FOR UPDATE employees SET salary = salary * 1.10 WHERE department_id = (SELECT department_id FROM departments WHERE location_id = 1200); 10) explain decode function in oracle Ans) DECODE function compares one expression to one or more other expressions and, when the base expression is equal to a search expression, it returns the corresponding result expression; or, when no match is found, returns the default expression when it is specified, or NA when 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 command but it reads all blocks and checks for corruptions. If it finds corrupted blocks it will place the information about the corruption into a view:

v$database_block_corruption; Now we can tell RMAN to recover all the blocks which 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 using pipes. 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 defined as below dbms_pipe.create_pipe(dbms_pipe.unique_session_name) -- Creates a PIPE based on your unique 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 the data 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 and raw data use the corresponding DBMS_PIPE.PACK_MESSAGE_RAW method. This procedure basically places the data into buffer which can be send on any pipe using the dbms_pipe.send_message(pipename) function. (3) At the other end of the pipe you can receive the data using dbms_pipe.receive_message function. This functions fetches the data into buffer from where you can unpack the data using dbms_pipe.unpack_message function. This function gets the data in the buffer into a message buffer. These are the basic commands that you can use for working with pipes. For more details visit oracle 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 the database is open connections are limited only to those whose user accounts have been granted the RESTRICTED SESSION system privilege. 14) You have just had to restore from backup and do not have any control files. How would you go about bringing up this database? Ans) I would create a text based backup control file, stipulating where on disk all the data files where and then issue the recover command with the using backup control file clause. Alter database backup controlfile to trace;

15) How would you go about increasing the buffer cache hit ratio? Use the buffer cache advisory over a given workload and then query the v$db_cache_advice table. If a change was necessary then I would use the alter system set db_cache_size command. 16) Can one use dynamic SQL within PL/SQL? OR Can you use a DDL in a procedure ? How ? Ans ) From PL/SQL V2.1 one can use the DBMS_SQL package to execute dynamic SQL statements. Eg: CREATE OR REPLACE PROCEDURE DYNSQL AS cur integer; rc integer; BEGIN cur := 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/A to reset SQL> Set NULL 2. Change SQL prompt name SQL> 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 Words SQL> select sal, (to_char(to_date(sal,'j'), 'jsp')) from emp; the output like, SAL (TO_CHAR(TO_DATE(SAL,'J'),'JSP')) --------- ----------------------------------------------------800 eight hundred 1600 one thousand six hundred 1250 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 a single value. Your example converts a Julian date value into a date with the inner TO_DATE nested 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 or initcaps.

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 where B.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) 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 an existing 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/SQL programs to protect the source code. Oracle provides a way to hide code with the PL/SQL Wrapper utility. When source code has been wrapped, 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 that it 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 proprietary algorithms and methods Even though the code is unreadable, it compiles without error. 8. 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 directory you 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*Plus SPOOL 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 information SQL> select banner from v$version; 10. How will you run DOS commands in SQL prompt? Ans : In Unix: ! In Win : $

3. Other way to replace query result null value with a text SQL> Set NULL N/A to reset SQL> Set NULL 4. Change SQL prompt name SQL> 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 Words SQL> select sal, (to_char(to_date(sal,'j'), 'jsp')) from emp; the output like, SAL (TO_CHAR(TO_DATE(SAL,'J'),'JSP')) --------- ----------------------------------------------------800 eight hundred 1600 one thousand six hundred 1250 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 a single value. Your example converts a Julian date value into a date with the inner TO_DATE nested 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 or initcaps.

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 where B.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 the maximum code size is 100K.You can run the following select statement to query the size of an existing 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/SQL programs to protect the source code. Oracle provides a way to hide code with the PL/SQL Wrapper utility. When source code has been wrapped, 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 that it 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 proprietary algorithms and methods Even 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 directory you 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*Plus SPOOL 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;

13. To view installed Oracle version information SQL> 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 a procedure 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 currently using. The usual fix involves either use of views or temporary tables so the database is selecting from 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 many which 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 tables PL/SQL tables are scalar arrays that can be referenced by a binary integer. They can be used to hold values for use in later queries or 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, nonstored 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 if you 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

used in exception handling to report, or, store in an error log table, the error that occurred in the code. These are especially useful for the WHEN OTHERS exception. 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 the SHOW ERROR command, but this only shows errors. The DBMS_OUTPUT package can be used to show intermediate results from loops and the status of variables as the procedure is executed. The new package UTL_FILE can also be used. 11. What are the types of triggers? Expected Answer: There are 12 types of triggers in PL/SQL that consist of combinations of the BEFORE, AFTER, ROW, TABLE, INSERT, UPDATE, DELETE and ALL key words: BEFORE ALL ROW INSERT AFTER ALL ROW INSERT BEFORE INSERT AFTER INSERT etc. 12.What's Mutating Table Mutating Table is a table that is currently being modified by an Insert, Update or Delete statement. Constraining Table is a table that a triggering statement might need to read either directly for a SQL statement or indirectly for a declarative Referential Integrity constraints. Pseudo Columns 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 parent statement. Parent statement can be Select, Update or Delete. Use CRSQ to answer multipart questions 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 the package 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 ?

Applications that have outgrown their environment are re-engineered to run in a larger environment. 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 emp Where emp_no+' '=12345; i.e you have to concatenate the column name with space within codes in the where condition. 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 NOTFOUND returns 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 a value

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 a value for every row in a table. The ROWID gives us the physical address of a row and is the fastest way to access 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.0002 The ROWID has three important uses it is :-

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 clause or in ORDER BY clause. Also we cannot add primary key constraint to that column only not to the whole table that means we will give primary key to any column in the table except the column having the long data type. If we give we get the error ORA-02269: key column 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 low distinct values such as GENDER MARITAL_STATUS and RELATION. This assumption is not completely accurate however. In reality a bitmap index is always advisable for systems in which data is not frequently updated by many concurrent systems. In fact as I'll demonstrate here a bitmap index on a column with 100-percent unique values (a column candidate for primary key) is as efficient as a B-tree index. There are several disadvantages to using a bitmap index on a unique column one being the need for sufficient space (and Oracle does not recommend it). However the size of the bitmap index depends on the cardinality of the column on which it is created as well as the data distribution. Consequently a bitmap index on the GENDER column will be smaller than a B-tree index on the same column. In contrast a bitmap index on EMPNO (a candidate for primary key) will be much larger than a B-tree index on this column. But because fewer users access decision-support systems (DSS) systems than would access 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 of the database are copied (image copy). The datafiles do not change during the copy so the database is in sync upon restore. Used when:Service level allows for some down time for backup Hot backup is a physical backup. In a hot backup the database remains open and available to users. All files of the database are copied (image copy). There may be changes to the database as the copy is made and so all log files of changes being made during the backup must be saved too. Upon a restore the changes in the log files are reapplied to bring the database in sync. Used when:

A full backup of a database is needed Service 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 parts 1. Specification - declares types,functions,procedures,exceptions,cursors 2. Body - implements the specification Whenevr a func/proc is referenced from the pkg thn the entire pkg is loaded in the memory so tht whn a diff func from the same pkg 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 a where 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 on sys.dual table or public synonym dual. CREATE TABLE DUAL(COL1 VARCHAR(1)); select sysdate from dual insert into dual values('X') commit insert 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;

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 the column value contains LOVELY the reverse-key index will be YLEVOL. This index very much useful where users issues the select command with where clause such as WHERE x 5 but it will not be useful for searching in range say WHERE x between 2 and 6. 12 Reverse 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 associated with 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 statement if 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 very similar to the dense_rank function. However, the rank function can cause non-consecutive rankings if the tested values are the same. 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 function select 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 a bonus of $500 from within the employees table.

Analytic function select employee_name, salary, rank() OVER (PARTITION BY department ORDER BY salary) from employees where department = 'Marketing'; The SQL statement above would return all employees who work in the Marketing department and then calculate a rank for each unique salary in the Marketing department. If two employees had the same salary, the rank function would return the same rank for both employees. However, this will cause a gap in the ranks (ie: non-consecutive ranks). This is quite different from the dense_rank function which generates consecutive rankings.

12-->What is partitioning ? Partitioning can provide tremendous benefits to a wide variety of applications by improving manageability, performance, and availability. It is not unusual for partitioning to improve the performance of certain queries or maintenance operations 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 toughest problems posed by cutting-edge applications. Partitioning is a key tool for building multi-terabyte systems or systems with extremely high availability requirements. Basics of Partitioning Partitioning allows a table, index or index-organized table to be subdivided into smaller pieces. Each piece of database object is called a partition. Each partition has its own name, and may optionally have its own storage characteristics, such as having table compression enabled or being stored in different tablespaces. From the perspective of a database administrator, a partitioned object has multiple pieces which can be managed either collectively or individually. This gives the administrator considerably flexibility in 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 accessing a partitioned table using SQL DML commands. Tables are partitioned using a 'partitioning key', a set of columns which determine in which partition a given row will reside. Oracle9i provides five techniques for partitioning tables: Range Partitioning: Each partition is specified by a range of values of the partitioning key (for a table 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 table with 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 for a given row

Composite Range-Hash Partitioning: A combination of the Range and Hash partitioning technique. The table is first range-partitioned, and then each individual range-partition is further sub-partitioned using the hash partitioning technique. All subpartitions for a given range partition together represent 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 each individual range-partition is further sub-partitioned using a list partitioning technique. Unlike composite Range-Hash partitioning, the content of each sub-partition represents a logical subset of the data, described by its appropriate Range and List partition setup.

Difference between implicit and explicit cursors 1. imlicit cursors are faster 2. implicit cursors includes a NO_DATA_FOUND and a TOO_MANY_ROWS exception check. CREATE OR REPLACE PROCEDURE cursor_comparison AS l_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 LOOP OPEN 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

SET SERVEROUTPUT ON EXEC cursor_comparison ; Explicit : 203 Implicit : 162 The volume of code being used . PL/SQL is an interpreted language so every extra line of code adds to the total processing time. As a rule of thumb, make the code as compact as possible without 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/SQL table, 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/SQL tables.

explain plan

Whenever you read or write data in Oracle, you do so by issuing an SQL statement. One of Oracle's task when it receives such a statement is to build a query execution plan. An execution plan defines how Oracle finds or writes the data. For example, an important decision that Oracle has to take is if it uses indexes or not. And if there are more indexes, which of these is used. All this is contained in an execution plan. If one wants to explore such an execution plan, Oracle provides the SQL statement EXPLAIN PLAN to determine this. The general syntax of EXPLAIN PLAN is: explain plan for sql-statement; explain plan set statement_id='some identifier' for sql-statement; explain plan set statement_id='some identifier' into table_name for sql-statement; explain plan into table_name for sql-statement; If you do an EXPLAIN PLAN, Oracle will analyze the statment and fill a special table with the Execution plan for that statement. You can indicate which table has to be filled with the following SQL command: explain plan into table_name for your-precious-sql-statement; If you omit the INTO TABLE_NAME clause, Oracle fills a table named PLAN_TABLE by default.

The Plan Table The plan table is the table that Oracle fills when you have it explain an execution plan for an SQL statement. You must make sure such a plan table exists. Oracle ships with the script UTLXPLAN.SQL which creates this table, named PLAN_TABLE (which is the default name used by EXPLAIN PLAN). If you like, however, you can choose any other name for the plan table, as long 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, and parent_id. The pair operation and object_name define what operation would be done on (or with) object_name. If an operation has an id which other operations have as parent_id, it means the 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 TABLE ACCESS can have the options: FULL or BY ROWID or many others. Full in this case means, that the 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 to access the table shorter. dbms_xplan As of 9i, dbms_xplan can be used to format the plan table. SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY);

Example 9-4 Using EXPLAIN PLAN with the INTO Clause EXPLAIN PLAN INTO my_plan_table FOR SELECT last_name FROM employees; AUTOTRACE - The Easy Option? Switching on the AUTOTRACE parameter in SQL*Plus causes an explain to be performed on every query. SQL> SET AUTOTRACE ON SQL> 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=CHOOSE 1 0 NESTED LOOPS 2 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 calls 4 db block gets 27 consistent gets 0 physical reads 0 redo size 941 bytes sent via SQL*Net to client 425 bytes received via SQL*Net from client 2 SQL*Net roundtrips to/from client 0 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 the execution plan the statement must be run to completion. If the query is particularly inefficient and/or returns many rows, this may take a considerable time. At first glance, using the TRACEONLY option of AUTOTRACE seems to remove this issue, but this option merely supresses the output of the query data, it doesn't prevent the statement being run. As such, long running queries will still take a long time to complete, but they will not present their data. The following example show this in practice. <BLOCKQUOTE

The query takes the same time to return (about 10 seconds) whether the TRACEONLY option is used or not. If the TRACEONLY option prevented the query running, you would expect it to return instantly, like an EXPLAIN PLAN. EXPLAIN PLAN The EXPLAIN PLAN method doesn't require the query to be run, greatly reducing the time it takes to get an execution plan for long-running queries compared to AUTOTRACE. First the query must be explained: SQL> EXPLAIN PLAN FOR 2 SELECT * 3 FROM emp e, dept d 4 WHERE e.deptno = d.deptno 5 AND e.ename = 'SMITH'; Explained. SQL> Then the execution plan displayed: SQL> @$ORACLE_HOME/rdbms/admin/utlxpls.sql Plan 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 script instead of utlxpls.sql. Statement ID If multiple people are accessing the same plan table, or you would like to keep a history of the execution plans you should use the STATEMENT_ID. This associates a user specified ID with each plan which can be used when retrieving the data. SQL> EXPLAIN PLAN SET STATEMENT_ID = 'TIM' FOR 2 SELECT * 3 FROM emp e, dept d 4 WHERE e.deptno = d.deptno 5 AND e.ename = 'SMITH'; Explained. SQL> @explain.sql TIM

PLAN OBJECT_NAME OBJECT_TYPE BYTES COST PARTITION_START PARTITION_STOP -------------------------------------- --------------- --------------- ----- ----- --------------- --------------Select Statement 57 4 1.1 Nested Loops 57 4 2.1 Table Access (Full) EMP TABLE 37 3 2.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 a statement_id parameter. You can easily modify the scripts or you can use the script 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 modified directly through DML statements (INSERT, UPDATE, and DELETE). These triggers are called INSTEAD OF triggers because, unlike other types of triggers, Oracle fires the trigger instead of executing the triggering statement. You can write normal INSERT, UPDATE, and DELETE statements against the view and the INSTEAD OF trigger is fired to update the underlying tables appropriately. INSTEAD OF triggers are 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 using INSTEAD OF triggers and if it conforms to the restrictions listed as follows. If the view query contains any of the following constructs, the view is not inherently modifiable and you therefore cannot 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 UPDATE statement that does not refer to any of the pseudocolumns or expressions CREATE TABLE Project_tab ( Prj_level NUMBER,

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 INSTEAD OF trigger for inserting rows into the MANAGER_INFO view. CREATE OR REPLACE VIEW manager_info AS SELECT e.ename, e.empno, d.dept_type, d.deptno, p.prj_level, p.projno FROM Emp_tab e, Dept_tab d, Project_tab p WHERE e.empno = d.mgr_no AND d.deptno = p.resp_dept; CREATE OR REPLACE TRIGGER manager_info_insert INSTEAD OF INSERT ON manager_info REFERENCING NEW AS n -- new manager information FOR EACH ROW DECLARE 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.ename WHERE Emp_tab.empno = :n.empno; END IF; SELECT COUNT(*) INTO rowcnt FROM Dept_tab WHERE deptno = :n.deptno; IF rowcnt = 0 THEN INSERT INTO Dept_tab (deptno, dept_type) VALUES(:n.deptno, :n.dept_type); ELSE UPDATE Dept_tab SET Dept_tab.dept_type = :n.dept_type WHERE Dept_tab.deptno = :n.deptno; END IF; SELECT COUNT(*) INTO rowcnt FROM Project_tab WHERE Project_tab.projno = :n.projno;

IF rowcnt = 0 THEN INSERT INTO Project_tab (projno, prj_level) VALUES(:n.projno, :n.prj_level); ELSE UPDATE Project_tab SET Project_tab.prj_level = :n.prj_level WHERE Project_tab.projno = :n.projno; END IF; END;

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

1. select * from recyclebin create table yyy as select * from ACC_INSTL_PLAN_ITEM drop table yyy flashback table yyy to before drop

2. Display the number value in Words SQL> select sal, (to_char(to_date(sal,'j'), 'jsp')) from emp; the output like, SAL (TO_CHAR(TO_DATE(SAL,'J'),'JSP')) --------- ----------------------------------------------------800 eight hundred 1600 one thousand six hundred 1250 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 a single value. Your example converts a Julian date value into a date with the inner TO_DATE nested 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 or initcaps.

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 where B.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)

You might also like