You are on page 1of 90

Basic DBMS Interview Questions And Answers For Freshers

Data base management system (DBMS) is software, which is a collection of programs that enable user to create, modify, alter and delete the data. There are different types of DBMS ranging from small systems to mainframes used for huge process. Storing data can also be done using files but DBMS allows you to save the data easily and access it easily by providing security, reducing redundancy. Thus resulting data integrity, maintaining data base. (Q) Describe the level of data abstraction? (A) There are three levels for data abstraction Physical level: The lowest level of abstraction describes how data are stored Logical level: Next higher level in abstraction, describes which data is stored and relation between them View Level: This describes the part of entire database (Q) List the advantages of DBMS? (A) Here is the list of advantages of using DBMS 1. Redundancy is controlled. (Duplication is controlled) 2. Unauthorized access is restricted. (Restriction others to access data base information) 3. Providing multiple user interfaces. (Providing multi user access also limiting their permission) 4. Enforcing integrity constraints. 5. Providing backup and recovery. (Back memory provided when data base crash occurs) (Q) What is DBMS? (A) DBMS is software that provides the user process of defining, creating, altering the data for various applications. (Q) When we give SELECT * FROM EMP; How does oracle respond: (A) When we ask the query SELECT * FROM EMP; the database server check all the data in the EMP file and it displays the data of the EMP file on the screen. (Q) What is the difference between VARCHAR() and VARCHAR2()? (A) Varchar means fixed length character data (size) i.e., min size-1 and max-2000 Varchar2 means variable (Dynamic) length character data i.e., min-1 to max-4000 (Q) Which command displays the SQL command in the SQL buffer, and then executes it? (A) LIST or L command is used to get the recent one from SQL Buffer. (Q) What is Difference between DBMS and File System? (A) DBMS and File system are two ways of saving data, including managing data. File System: It is a collection of raw data files stored in hard drive. DBMS: It is a bundle of application that is dedicated for managing data stored in databases

In File System, files are used to store data while, collections of databases are utilized for the storage of data in DBMS. In file system storing altering data done manually. DBMS provide automated methods to complete managing data. (Q) What is difference between DELETE and TRUNCATE? (A) Both the commands are used to delete or remove the data from table, where as TRUNCATE is a DDL command and it can`t be rolled back. DELETE is a DML command and it can be roll back. TRUNCATE deletes the data permanently while using DELETE we can again get back the data.(ROLL back). (Q) What is advantage of using trigger? (A) Trigger used when we need to validate a DML statement that modifies a table. Also to update automatically when DML command is executed. Triggers can be used to enforce constraints. (Q) What is use of WITH GRANT OPTION and GRANT command? (A) These commands give privilege to grant his/her privileges to other users. (Q) What is difference between SQL and SQL SERVER? (A) SQL (sequel) is a language that provides an interface to RDBMS, developed by IBM. SQL SERVER is a RDBMS just like Oracle, DB2. (Q) Write a query to find second maximum value from a table? (A) select max (sal) from tname where sal= (select max (sal) from tname where sal< (select max (sal) from tname); (Q) Write a query that returns only duplicate rows with number of times they are repeated, if table has duplicate values? (A) SELECT COL1 FROM TAB1 WHERE COL1 IN (SELECT MAX (COL1) FROM TAB1 GROUP BY COL1 HAVING COUNT (COL1) > 1) - See more at: http://thestudentdaily.com/2011/11/dbms-interview-questions-and-answers-forfrehsers/990/#sthash.CgivmO0S.dpuf

SQL is not itself a database management system, nor is it a stand-alone product. You cannot go into a computer store and buy SQL. Then.

What is sql? Structured Query Language (SQL) is a language that provides an interface to relational database systems. SQL was developed by IBM in the 1970s for use in System R, and is a de facto standard, as well as an ISO and ANSI standard. SQL is often pronounced SEQUEL. In common usage SQL also encompasses DML (Data Manipulation Language), for INSERTs, UPDATEs, DELETEs and DDL (Data Definition Language), used for creating and modifying tables and other database structures. The development of SQL is governed by standards. A major revision to the SQL standard was completed in 1992, called SQL2. SQL3 support object extensions and are (partially?) implemented in Oracle8 and 9. Sql interview questions: 1. Which is the subset of SQL commands used to manipulate Oracle Database structures, including tables? Data Definition Language (DDL) 2. What operator performs pattern matching? LIKE operator 3. What operator tests column for the absence of data? IS NULL operator 4. Which command executes the contents of a specified file? START <filename> or @<filename> 5. What is the parameter substitution symbol used with INSERT INTO command? & 6. Which command displays the SQL command in the SQL buffer, and then executes it? RUN 7. What are the wildcards used for pattern matching? _ for single character substitution and % for multi-character substitution 8. State true or false. EXISTS, SOME, ANY are operators in SQL. True 9. State true or false. !=, <>, ^= all denote the same operation. True

10. What are the privileges that can be granted on a table by a user to others? Insert, update, delete, select, references, index, execute, alter, all 11. What command is used to get back the privileges offered by the GRANT command? REVOKE 12. Which system tables contain information on privileges granted and privileges obtained? USER_TAB_PRIVS_MADE, USER_TAB_PRIVS_RECD 13. Which system table contains information on constraints on all the tables created? USER_CONSTRAINTS 14. TRUNCATE TABLE EMP; DELETE FROM EMP; Will the outputs of the above two commands differ? Both will result in deleting all the rows in the table EMP. 15. What is the difference between TRUNCATE and DELETE commands? TRUNCATE is a DDL command whereas DELETE is a DML command. Hence DELETE operation can be rolled back, but TRUNCATE operation cannot be rolled back. WHERE clause can be used with DELETE and not with TRUNCATE. 16. What command is used to create a table by copying the structure of another table? Answer : CREATE TABLE .. AS SELECT command Explanation : To copy only the structure, the WHERE clause of the SELECT command should contain a FALSE statement as in the following. CREATE TABLE NEWTABLE AS SELECT * FROM EXISTINGTABLE WHERE 1=2; If the WHERE condition is true, then all the rows or rows satisfying the condition will be copied to the new table - See more at: http://thestudentdaily.com/2010/11/sql-interview-questions-and-answers-forfreshers-pdf/481/#sthash.2VC0tEsR.dpuf

Pl/sql

PL/SQL collections - Nested, Varrays, Asso Arrays - Equivalent in database An example: SQL> create type mytype is table of number; 2/

Type created. SQL> create table t (id integer, tab mytype) nested table tab store as mytab; Table created. SQL> insert into t values (1, mytype(1,2,3)); 1 row created. SQL> select * from t; ID TAB ---------- -----------------------------1 MYTYPE(1, 2, 3) 1 row selected.

QL, PL/SQL AND SQL Plus Questions 1. Which of the following statements contains an error? a.. SELECT * FROM emp WHERE empid = 493945; b. SELECT empid FROM emp WHERE empid= 493945; c. SELECT empid FROM emp; d. SELECT empid WHERE empid = 56949 AND lastname = ?SMITH?; 2. Which of the following correctly describes how to specify a column alias? a. Place the alias at the beginning of the statement to describe the table. b. Place the alias after each column, separated by white space, to describe the column. c. Place the alias after each column, separated by a comma, to describe the column. d. Place the alias at the end of the statement to describe the table. 3. The NVL function a. Assists in the distribution of output across multiple columns. b. Allows the user to specify alternate output for non -null column values. c. Allows the user to specify alternate output for null column values. d Nullifies the value of the column output 4. Output from a table called PLAYS with two columns, PLAY_NAME and AUTHOR,is shown below. Which of the following SQL statements produced it? PLAY_TABLE |Midsummer Night?s Dream|, SHAKESPEARE |Waiting For Godot|, BECKETT |The Glass Menagerie|, WILLIAMS a SELECT play_name || author FROM plays; b SELECT play_name, author FROM plays;

c SELECT play_name||?, ? || author FROM plays; d SELECT play_name||?, ? || author PLAY_TABLE FROM plays; 5. Issuing the DEFINE_EDITOR=|emacs| will produce which outcome? a. The emacs editor will become the SQL*Plus default text editor. b. The emacs editor will start running immediately. c. The emacs editor will no longer be used by SQL*Plus as the default text editor. d. The emacs editor will be deleted from the system. 6. The user issues the following statement. What will be displayed if the EMPID selected is 60494? SELECT DECODE(empid,38475, |Terminated|,60494, |LOA|, |ACTIVE|)FROM emp; a. 60494 b. LOA c. Terminatedd. ACTIVE 7. SELECT (TO_CHAR(NVL(SQRT(59483), |INVALID|)) FROM DUAL is a valid SQL statement. a. TRUE b. FALSE 8. The appropriate table to use when performing arithmetic calculations on values defined within the SELECT statement (not pulled from a table column) is a. EMP b. The table containing the column values c. DUALD. An Oracle-defined table 9. Which of the following is not a group function? a. avg( ) c. sqrt( ) c. sum( ) d. max( ) 10. Once defined, how long will a variable remain so in SQL*Plus? a. Until the database is shut down b. Until the instance is shut down c. Until the statement completes d. Until the session completes 11. The default character for specifying runtime variables in SELECT statements is a. Ampersand b. Ellipses c. Quotation marks d. Asterisk 12. A user is setting up a join operation between tables EMP and DEPT. There are some employees in the EMP table that the user wants returned by the query, but the employees are not assigned to departments yet. Which SELECT statement is most appropriate for this user? a. select e.empid, d.head from emp e, dept d; b. select e.empid, d.head from emp e, dept d where e.dept# = d.dept#; c. select e.empid, d.head from emp e, dept d where e.dept# = d.dept# (+);

d. select e.empid, d.head from emp e, dept d where e.dept# (+) = d.dept#; 13. Developer ANJU executes the following statement: CREATE TABLE animals AS SELECT * from MASTER.ANIMALS; What is the effect of this statement? a. A table named ANIMALS will be created in the MASTER schema with the same data as the ANIMALS table owned by ANJU b. A table named ANJU will be created in the ANIMALS schema with the same data as the ANIMALS table owned by MASTER c. A table named ANIMALS will be created in the ANJU schema with the same data as the ANIMALS table owned by MASTER. d. A table named MASTER will be created in the ANIMALS schema with the same data as the ANJU table owned by ANIMALS. 14. User JANKO would like to insert a row into the EMPLOYEE table, which has three columns: EMPID, LASTNAME, and SALARY. The user would like to enter data for EMPID 59694, LASTNAME Harris, but no salary. Which statement would work best? a. INSERT INTO employee VALUES (59694,?HARRIS?, NULL); b. INSERT INTO employee VALUES (59694,?HARRIS?); c. INSERT INTO employee (EMPID, LASTNAME, SALARY) VALUES (59694,?HARRIS?); d. INSERT INTO employee (SELECT 59694 FROM ?HARRIS?); 15. Which three of the following are valid database datatypes in Oracle? (Choose three.) a. CHAR b. VARCHAR2 c. BOOLEAN d. NUMBER 16. Omitting the WHERE clause from a DELETE statement has which of the following effects? a. The delete statement will fail because there are no records to delete. b. The delete statement will prompt the user to enter criteria for the deletion c. The delete statement will fail because of syntax error. d. The delete statement will remove all records from the table. 17. Creating a foreign-key constraint between columns of two tables defined with two different datatypes will produce an error. a. TRUE b. FALSE 18. Dropping a table has which of the following effects on a nonunique index created for the table? a. No effect. b. The index will be dropped. c. The index will be rendered invalid. d. The index will contain NULL values. 19. To increase the number of nullable columns for a table, a. Use the alter table statement. b. Ensure that all column values are NULL for all rows. c. First increase the size of adjacent column datatypes, then add the column. d. Add the column, populate the column, then add the NOT NULL constraint.

20. Which line of the following statement will produce an error? a. CREATE TABLE goods b. (good_no NUMBER, c. good_name VARCHAR2 check(good_name in (SELECT name FROM avail_goods)), d. CONSTRAINT pk_goods_01 e. PRIMARY KEY (goodno)); f. There are no errors in this statement. 21. MAXVALUE is a valid parameter for sequence creation. a. TRUE b. FALSE 22. Which of the following lines in the SELECT statement below contain an error? a SELECT DECODE(empid, 58385, |INACTIVE|, |ACTIVE|) empid b. FROM emp c. WHERE SUBSTR(lastname,1,1) > TO_NUMBER(?S') d. AND empid > 02000 e. ORDER BY empid DESC, lastname ASC; f. There are no errors in this statement. 23. Which function below can best be categorized as similar in function to an IF -THEN-ELSE statement? a. SQRT b. DECODE c. NEW_TIME d. ROWIDTOCHAR 24. Which two of the following orders are used in ORDER BY clauses? (choose two) a. ABS b. ASC c. DESC d. DISC 26. Which of the following statements is true about implicit cursors? a. Implicit cursors are used for SQL statements that are not named. b. Developers should use implicit cursors with great care. c. Implicit cursors are used in cursor for loops to handle data processing. d. Implicit cursors are no longer a feature in Oracle. 27. Which of the following is not a feature of a cursor FOR loop? a. Record type declaration. b. Opening and parsing of SQL statements. c. Fetches records from cursor. d. Requires exit condition to be defined. 28. A developer would like to use referential datatype declaration on a variable. The variable name is EMPLOYEE_LASTNAME, and the corresponding table and column is EMPLOYEE, and LNAME, respectively. How would the developer define this variable using referential datatypes? a. Use employee.lname%type.

b. Use employee.lname%rowtype. c. Look up datatype for EMPLOYEE column on LASTNAME table and use that. d. Declare it to be type LONG. 29. Which three of the following are implicit cursor attributes? a. %found b. %too_many_rows c. %notfound d. %rowcount e. %rowtype 30. If left out, which of the following would cause an infinite loop to occur in a simple loop? a. LOOP b. END LOOP c. IF-THEN d. EXIT 31. Which line in the following statement will produce an error? a. cursor action_cursor is b. select name, rate, action c. into action_record d. from action_table; e. There are no errors in this statement. 32. The command used to open a CURSOR FOR loop is a. open b. fetch c. parse d. None, cursor for loops handle cursor opening implicitly. 33. What happens when rows are found using a FETCH statement a. It causes the cursor to close b. It causes the cursor to open c. It loads the current row values into variables d. It creates the variables to hold the current row values 34. CREATE OR REPLACE PROCEDURE find_cpt (v_movie_id ,ArgumentMode-NUMBER, v_cost_per_ticket ,argument mode- NUMBER)IS BEGIN IF v_cost_per_ticket > 8.5 THEN SELECT cost_per_ticket INTO v_cost_per_ticket FROM gross_receipt WHERE movie_id = v_movie_id; END IF; END; Which mode should be used for V_COST_PER_TICKET? a. IN b. OUT

c. RETURN d. IN OUT 35. CREATE OR REPLACE TRIGGER update_show_gross ,trigger informationBEGIN ,additional codeEND; The trigger code should only execute when the column, COST_PER_TICKET, is greater than $3.75. Which trigger information will you add? a. WHEN (new.cost_per_ticket > 3.75) b. WHEN (:new.cost_per_ticket > 3.75 c. WHERE (new.cost_per_ticket > 3.75) d. WHERE (:new.cost_per_ticket > 3.75) 36. What is the maximum number of handlers processed before the PL/SQL block is exited when an exception occurs? a. Only one b. All that apply c. All referenced d. None 37. For which trigger timing can you reference the NEW and OLD qualifiers? a. Statement and Row b. Statement only c. Row only d. Oracle Forms trigger 38. CREATE OR REPLACE FUNCTION get_budget(v_studio_id IN NUMBER) RETURN number ISv_yearly_budget NUMBER; BEGIN SELECT yearly_budget INTO v_yearly_budget FROM studio WHERE id = v_studio_id; RETURN v_yearly_budget; END; Which set of statements will successfully invoke this function within SQL*Plus? a VARIABLE g_yearly_budget NUMBER EXECUTE g_yearly_budget := GET_BUDGET(11); b. VARIABLE g_yearly_budget NUMBER EXECUTE :g_yearly_budget := GET_BUDGET(11); c. VARIABLE :g_yearly_budget NUMBER EXECUTE :g_yearly_budget := GET_BUDGET(11); d. VARIABLE g_yearly_budget NUMBER :g_yearly_budget := GET_BUDGET(11); 39.CREATE OR REPLACE PROCEDURE update_theater (v_name IN VARCHAR2, v_theater_id IN NUMBER) IS BEGIN UPDATE theater SET name = v_name WHERE id = v_theater_id; END update_theater;

When invoking this procedure, you encounter the error: ORA-00001: Unique constraint (SCOTT.THEATER_NAME_UK) violated.How should you modify the function to handle this error? a. An user defined exception must be declared and associated with the error code and handled in the EXCEPTION section. b. Handle the error in EXCEPTION section by referencing the error code directly. c. Handle the error in the EXCEPTION section by referencing the UNIQUE_ERROR predefined exception. d. Check for success by checking the value of SQL%FOUND immediately after the UPDATE statement. 40.CREATE OR REPLACE PROCEDURE calculate_budget IS v_budget studio.yearly_budget%TYPE; BEGIN v_budget := get_budget(11); IF v_budget

PL/SQL 1. What?s a PL/SQL table? Its purpose and Advantages? A. A PL/SQL table is one dimensional, indexed, unbounded sparsed collection of homogeneous Data. PLSQL tables are used to move data into and out of the database and between client side applications and stored sub-programs. They have attributes such as exits, prior, first, last, delete ,next . These attributes make PLSQL tables easier to use and applications easier to maintain. Advantages: ? PL\SQL tables give you the ability to hold multiple values in a structure in memory so that a PL\SQL block does not have to go to the database every time it needs to retrieve one of these values - it can retrieve it directly from the PL\SQL table in memory. ? Global temporary tables act as performance enhancers when compared to standard tables as they greatly reduce the disk IO. ? They also offer the ease-of-use of standard tables, since standard SQL can be used with them; no special array processing syntax is required. 2. What is a Cursor? How many types of Cursor are there? A) Cursor is an identifier/name to a work area that we can interact with to access its information. A cursor points to the current row in the result set fetched. There are three types of cursors. They are ? Implicit cursors ? created automatically by PL/SQL for all SQL-DML statements such as Insert Update, delete and Select ? Explicit cursors ? Created explicitly. They create a storage area where the set of rows Returned by a query are placed. ? Dynamic Cursors ? Ref Cursors( used for the runtime modification of the select querry). Declaring the cursor, Opening the cursor, Fetching data , Closing the cursor(Releasing the work area) are the steps involved when using explicit cursors. 3. What is the difference between Function and Procedure? ? Procedure is a sub program written to perform a set of actions and returns multiple values Using out parameters or return no value at all. ? Function is a subprogram written to perform certain computations and return a single value. 4. What are the modes for passing parameters to Oracle? A) There are three modes for passing parameters to subprograms

? IN - An In-parameter lets you pass values to the subprogram being called. In the subprogram it acts like a constant and cannot be assigned a value. ? OUT ? An out-parameter lets you return values to the caller of the subprogram. It acts like an initialized variable its value cannot be assigned to another variable or to itself. ? INOUT ? An in-out parameter lets you pass initial values to the subprogram being called and returns updated values to the caller. 5. What is the difference between Truncate and Delete Statement? ? Truncate ? Data truncated by using truncate statement is lost permanently and cannot be retrieved even by rollback. Truncate command does not use rollback segment during its execution, hence it is fast. ? Delete ? Data deleted by using the delete statement can be retrieved back by Rollback. Delete statement does not free up the table object allocated space. 6. What are Exceptions? How many types of Exceptions are there? A) Exceptions are conditions that cause the termination of a block. There are two types of exceptions ? Pre-Defined ? Predefined by PL/SQL and are associated with specific error codes. ? User-Defined ? Declared by the users and are rose on deliberate request. (Breaking a condition etc.) Exception handlers are used to handle the exceptions that are raised. They prevent exceptions from propagating out of the block and define actions to be performed when exception is raised. 7. What is a Pragma Exception_Init? Explain its usage? A) Pragma Exception_Init is used to handle undefined exceptions. It issues a directive to the compiler asking it to associate an exception to the oracle error. There by displaying a specific error message pertaining to the error occurred. Pragma Exception_Init (exception_name, oracle_error_name). 8. What is a Raise and Raise Application Error? A) Raise statement is used to raise a user defined exception. B) A raise application error is a procedure belonging to dbms_standard package. It allows to display a user defined error message from a stored subprogram. 8. What is the difference between Package, Procedure and Functions? ? A package is a database objects that logically groups related PL/SQL types, objects, and Subprograms. ? Procedure is a sub program written to perform a set of actions and can return multiple values. ? Function is a subprogram written to perform certain computations and return a single value. Unlike subprograms packages cannot be called, passed parameters or nested. 9. How do you make a Function and Procedure as a Private? A) Functions and Procedures can be made private to a package by not mentioning their declaration in the package specification and by just mentioning them in the package body. 10. What is an Anonymous block? A) Anonymous Block is a block of instructions in PL/SQL and SQL which is not saved under a name as an object in database schema. It is also not compiled and saved in server storage, so it needs to be parsed and executed each time it is run. However, this simple form of program can use variables, can have flow of control logic, can return query results into variables and can prompt the user for input using the SQL*Plus '&' feature as any stored procedure. 12. What are the two basic parameters that we have to pass while registering PL/SQL procedure? A) Error code and Error Buffer. 11. How do you kick a Concurrent program from PL/SQL? A) Using FND_SUBMIT.SUBMIT_REQUEST. 12. How to display messages in Log file and Output file? A) Using FND_FILE.PUT_LINE

13. What is a Trigger ? How many types of Triggers are there? A) Trigger is a procedure that gets implicitly executed when an insert/update/delete statement is issued against an associated table. Triggers can only be defined on tables not on views, how ever triggers on the base table of a view are fired if an insert/update/delete statement is issued against a view. There are two types of triggers, Statement level trigger and Row level trigger. Insert After / For each row Trigger is fired / Update / Before / For Each statement Delete 14. Can we use Commit in a Database Trigger, if ?No? then why? A) No. Committing in a trigger will violate the integrity of the transaction. 15. What is Commit, Rollback and Save point? Commit ? Makes changes to the current transaction permanent. It Erases the savepoints and releases the transaction locks. Savepoint ?Savepoints allow to arbitrarily hold work at any point of time with option of later committing. They are used to divide transactions into smaller portions. Rollback ? This statement is used to undo work. 16. What is the difference between DDL, DML and DCL structures? A) DDL statements are used for defining data. Ex: Create, Alter, Drop. DML statements are used for manipulating data. Ex: Insert, update, truncate, delete, select. DCL statements are used for to control the access of data. Ex; Grant, Revoke. 17. How can u create a table in PL/SQL procedure? A) By using execute immediate statement we can create a table in PLSQL. Begin Execute immediate ?create table amit as select * from emp?; End; All DDL,DML,DCL commands can be performed by using this command. 18. How do we Tune the Queries? A) Queries can be tuned by Checking the logic (table joins), by creating Indexes on objects in the where clause, by avoiding full table scans. Finally use the trace utility to generate the trace file, use the TK -Prof utility to generate a statistical a nalysis about the query using which appropriate actions can be taken. 21. What is Explain Plan? How do u use Explain Plan in TOAD? A) It is a utility provided by toad that gives the statistics about the performance of the query. It gives information such as number of full table scans occurred, cost, and usage of indexes 19. What is a TK-PROF and its usage? A) Tk-Prof is a utility that reads the trace files and generates more readable data that gives the statistics about the performance of the query on a line to line basis. 20. What is Optimization? How many types of Optimization are there? A) Rule based Optimization and Cost Based Optimization. 21. What is the default optimization chosen by Oracle? A) Cost based Optimization. 22. What is the difference between When no data Found and cursor attribute % DATA FOUND? A) When no Data Found is a predefined internal exception in PLSQL. Where as % Data found is a cursor attribute that returns YES when zero rows are retrieved and returns NO when at least one row is retrieved. 23. What is the difference between the snapshot and synonym? ? A snapshot refers to read-only copies of a master table or tables located on a remote node. A snapshot can be queried, but not updated; only the master table can be updated. A snapshot is periodically refreshed to reflect

changes made to the master table. In this sense, a snapshot is really a view with periodicity. ? A synonym is an alias for table, view, sequence or program unit. They are of two types private and public. 25. What is the difference between data types char and varchar? A) Char reserves the number of memory locations mentioned in the variable declarations, even though not used (it can store a maximum of 255 bytes). Where as Varchar does not reserve any memory locations when the variable is declared, it stores the values only after they are assigned (it can store a maximum of 32767 bytes). 26. How can we place index to a second column in the table i.e. there is already one index and I want to place another index for the column on the table? 27. Items are imported from the legacy system using the item import interface using the SRS. How are items imported using the UNIX /PLSQL commands with out using SRS? A) From the operating system, use CONCSUB to submit a concurrent program. It's an easiest way to test a concurrent program. Normally, CONCSUB submits a concurrent request and returns control to the OS prompt/shell script without waiting for the request to complete. The CONCSUB WAIT parameter can be used to make CONCSUB wait until the request has completed before returning control to the OS prompt/shell script By using the WAIT token, the utility checks the request status every 60 seconds and returns to the operating system prompt upon completion of the request. concurrent manager does not abort, shut down, or start up until the concurrent request completes. If your concurrent program is compatible with itself, we can check it for data integrity and deadlocks by submitting it many times so that it runs concurrently with itself. Syntax: CONCSUB <ORACLE ID> <Responsibility Application Short Name> <Responsibility Name> <User Name> *WAIT=<Wait Flag+ CONCURRENT <Concurrent Program Application Short Name> <Concurrent Program Name> *START=<Requested Start Date>+ *REPEAT_DAYS=<Repeat Interval>+ *REPEAT_END=<Request Resubmission End Date>+ <Concurrent Program Arguments ...> To pass null parameters to CONCSUB, use '""' without spaces for each null parameter. In words: single quote double quote double quote single quote Following is an example of CONCSUB syntax with null parameters: CONCSUB oe/oe OE 'Order Entry Super User' JWALSH CONCURRENT XOE XOEPACK 4 3 '""' 3 B) To Invoke a Concurrent Program using PL/SQL: i) Just insert a row in FND_CONCURRENT_REQUESTS with the apropriate parameters and commit. ii) Invoke the SUBMIT_REQUEST procedure in FND_REQUEST package. FND_REQUEST.SUBMIT_REQUEST( 'AR', 'RAXMTR', '', '', FALSE, 'Autoinvoice Master Program', sc_time, FALSE, 1, 1020, 'VRP', '01-JAN-00', chr(0), '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''); 28. What is pipelining? 29) How can the duplicate records be from the table? SQL> create table table_name2 as select distinct * from table_name1; SQL> drop table_name1; SQL> rename table_name2 to table_name1; 30) What is the significance of _all tables? A) _all tables are multi-org tables which are associated with the company as a whole. Multiple Organizations is enabled in Oracle

Applications by partitioning some database tables by the Operating Unit. Other tables are shared across Operating Units (and therefore across set of books). Examples of Applications with partitioned tables are Oracle Payables, Oracle Purchasing, Oracle Receivables, Oracle Projects, Oracle Sales & Marketing etc. The name of each corresponding partitioned table is the view name appended by '_ALL' 31)What are mutating tables? And what is mutating error? A) A mutating table is a table that is currently being modified by an UPDATE, DELETE, or INSERT statement, or it is a table that might need to be updated by the effects of a declarative DELETE CASCADE referential integrity constraint. A mutating error occurs when a trigger which fires when updation/deletion/insertion is done on a table A performs insertion/updation/deletion on the same table A. This error results in an infinite loop which is termed as a mutating error. 32) What is difference between oracle 7 and oracle 8? A) Oracle 7 is a simple RDBMS, where as Oracle 8 is ORDBMS i.e., RDBMS with Object Support. The main add-ons in version 8 are? ? ? ? ? ? Abstract Data types Varrays PL/SQL Tables Nested Tables Partitioned Tables

33.What is Data cleaning and testing. A) Data Cleaning: Transformation of data in its current state to a pre-defined, standardized format using packaged software or program modules. Data Testing: The agreed upon conversion deliverables should be approved by the client representatives who are responsible for the success of the conversion. In addition, three levels of conversion testing have been identified and described in the prepare conversion test plans deliverables. Eg: for Summary Balances in GL we set Test Criteria as Record Counts, Hash Totals, Balances, Journal Debit and Credit. 34. While registering a report and a pl/sql block we pass some parameters, for any pl/sql block we pass 2 additional parameters. Can u list them? A) It requires two IN parameters for a PL/SQL procedure that's registered as a concurrent program in Apps. They are 1. Errcode IN VARCHAR2 2. Errbuff IN VARCHAR2 35) what is a trace file? A) when ever an internal error is detected by a process in oracle it dumps the information about the error into a trace file. Alter session set sql_trace=TRUE 36 ) When do you use Ref Cursors? We base a query on a ref cursor when you want to: i) More easily administer SQL ii) Avoid the use of lexical parameters in your reports iii) Share data sources with other applications, such as Form Builder

iv) Increase control and security v) Encapsulate logic within a subprogram

The most important DDL statements in SQL are: CREATE TABLE - creates a new database table ALTER TABLE - alters (changes) a database table DROP TABLE - deletes a database table CREATE INDEX - creates an index (search key) DROP INDEX - deletes an index 2. Operators used in SELECT statements. = Equal <> or != Not equal > Greater than < Less than >= Greater than or equal <= Less than or equal BETWEEN Between an inclusive range LIKE Search for a pattern 3. SELECT statements: SELECT column_name(s) FROM table_name SELECT DISTINCT column_name(s) FROM table_name SELECT column FROM table WHERE column operator value SELECT column FROM table WHERE column LIKE pattern SELECT column,SUM(column) FROM table GROUP BY column SELECT column,SUM(column) FROM table GROUP BY column HAVING SUM(column) condition value Note that single quotes around text values and numeric values should not be enclosed in quotes. Double quotes may be acceptable in some databases. 4. The SELECT INTO Statement is most often used to create backup copies of tables or for archiving records. SELECT column_name(s) INTO newtable *IN externaldatabase+ FROM source SELECT column_name(s) INTO newtable *IN externaldatabase+ FROM source WHERE column_name operator value 5. The INSERT INTO Statements: INSERT INTO table_name VALUES (value1, value2,....) INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,....) 6. The Update Statement: UPDATE table_name SET column_name = new_value WHERE column_name = some_value The Delete Statements: DELETE FROM table_name WHERE column_name = some_value Delete All Rows: DELETE FROM table_name or DELETE * FROM table_name 8. Sort the Rows: SELECT column1, column2, ... FROM table_name ORDER BY columnX, columnY, .. SELECT column1, column2, ... FROM table_name ORDER BY columnX DESC SELECT column1, column2, ... FROM table_name ORDER BY columnX DESC, columnY ASC 9. The IN operator may be used if you know the exact value you want to return for at least one of the columns.

SELECT column_name FROM table_name WHERE column_name IN (value1,value2,..) 10. BETWEEN ... AND SELECT column_name FROM table_name WHERE column_name BETWEEN value1 AND value2 The values can be numbers, text, or dates. 11. What is the use of CASCADE CONSTRAINTS? When this clause is used with the DROP command, a parent table can be dropped even when a child table exists. 12. Why does the following command give a compilation error? DROP TABLE &TABLE_NAME; Variable names should start with an alphabet. Here the table name starts with an '&' symbol.

Which system tables contain information on privileges granted and privileges obtained? USER_TAB_PRIVS_MADE, USER_TAB_PRIVS_RECD 14. Which system table contains information on constraints on all the tables created?obtained? USER_CONSTRAINTS. 15. What is the difference between TRUNCATE and DELETE commands? < TRUNCATE. with not and DELETE used be can clause WHERE back. rolled cannot operation TRUNCATE but back, Hence command. DML a is whereas command DDL> 16. State true or false. !=, <>, ^= all denote the same operation? True. 17. State true or false. EXISTS, SOME, ANY are operators in SQL? True. 18. What will be the output of the following query? SELECT REPLACE(TRANSLATE(LTRIM(RTRIM('!! ATHEN !!','!'), '!'), 'AN', '**'),'*','TROUBLE') FROM DUAL;? TROUBLETHETROUBLE. What does the following query do? SELECT SAL + NVL(COMM,0) FROM EMP;? This displays the total salary of all employees. The null values in the commission column will be replaced by 0 and added to salary. 20. What is the advantage of specifying WITH GRANT OPTION in the GRANT command? The privilege receiver can further grant the privileges he/she has obtained from the owner to any other user. 21. Which command executes the contents of a specified file? START or @. 22. What is the value of comm and sal after executing the following query if the initial value of ?sal? is 10000 UPDATE EMP SET SAL = SAL + 1000, COMM = SAL*0.1;? sal = 11000, comm = 1000. 23. Which command displays the SQL command in the SQL buffer, and then executes it? RUN. 24. What command is used to get back the privileges offered by the GRANT command? REVOKE.

25. What will be the output of the following query? SELECT DECODE(TRANSLATE('A','1234567890','1111111111'), '1','YES', 'NO' );? NO. Explanation : The query checks whether a given string is a numerical digit. 26. Which date function is used to find the difference between two dates? MONTHS_BETWEEN. 27. What operator performs pattern matching? LIKE operator.

28. What is the use of the DROP option in the ALTER TABLE command? It is used to drop constraints specified on the table. 29. What operator tests column for the absence of data? IS NULL operator. 30. What are the privileges that can be granted on a table by a user to others? Insert, update, delete, select, references, index, execute, alter, all. 31. Which function is used to find the largest integer less than or equal to a specific value? FLOOR. 32. Which is the subset of SQL commands used to manipulate Oracle Database structures, including tables? Data Definition Language (DDL). 33. What is the use of DESC in SQL? DESC has two purposes. It is used to describe a schema as well as to retrieve rows from table in descending order. Explanation : The query SELECT * FROM EMP ORDER BY ENAME DESC will display the output sorted on ENAME in descending order. 34. What command is used to create a table by copying the structure of another table? CREATE TABLE .. AS SELECT command Explanation: To copy only the structure, the WHERE clause of the SELECT command should contain a FALSE statement as in the following. CREATE TABLE NEWTABLE AS SELECT * FROM EXISTINGTABLE WHERE 1=2; If the WHERE condition is true, then all the rows or rows satisfying the condition will be copied to the new table. 35. TRUNCATE TABLE EMP; DELETE FROM EMP; Will the outputs of the above two commands differ? Both will result in deleting all the rows in the table EMP.. 36. What is the output of the following query SELECT TRUNC(1234.5678,-2) FROM DUAL;? 1200. 37. What are the wildcards used for pattern matching.? _ for single character substitution and % for multi-character substitution. 38. What is the parameter substitution symbol used with INSERT INTO command? &

QL 1. Which is the subset of SQL commands used to manipulate Oracle Database structures, including tables? Data Definition Language (DDL) 2. What operator performs pattern matching? LIKE operator 3. What operator tests column for the absence of data? IS NULL operator 4. Which command executes the contents of a specified file? START <filename> or @<filename>

5. What is the parameter substitution symbol used with INSERT INTO command? & 6. Which command displays the SQL command in the SQL buffer, and then executes it? RUN 7. What are the wildcards used for pattern matching? _ for single character substitution and % for multi-character substitution 8. State true or false. EXISTS, SOME, ANY are operators in SQL. True 9. State true or false. !=, <>, ^= all denote the same operation. True 10. What are the privileges that can be granted on a table by a user to others? Insert, update, delete, select, references, index, execute, alter, all 11. What command is used to get back the privileges offered by the GRANT command? REVOKE 12. Which system tables contain information on privileges granted and privileges obtained? USER_TAB_PRIVS_MADE, USER_TAB_PRIVS_RECD 13. Which system table contains information on constraints on all the tables created? USER_CONSTRAINTS 14. TRUNCATE TABLE EMP; DELETE FROM EMP; Will the outputs of the above two commands differ? Both will result in deleting all the rows in the table EMP. 15. What is the difference between TRUNCATE and DELETE commands? TRUNCATE is a DDL command whereas DELETE is a DML command. Hence DELETE operation can be rolled back, but TRUNCATE operation cannot be rolled back. WHERE clause can be used with DELETE and not with TRUNCATE. 16. What command is used to create a table by copying the structure of another table? Answer : CREATE TABLE .. AS SELECT command Explanation : To copy only the structure, the WHERE clause of the SELECT command should contain a FALSE statement as in the following. CREATE TABLE NEWTABLE AS SELECT * FROM EXISTINGTABLE WHERE 1=2; If the WHERE condition is true, then all the rows or rows satisfying the condition will be copied to the new table. 17. What will be the output of the following query? SELECT REPLACE(TRANSLATE(LTRIM(RTRIM('!! ATHEN !!','!'), '!'), 'AN', '**'),'*','TROUBLE') FROM DUAL; TROUBLETHETROUBLE

18. What will be the output of the following query? SELECT DECODE(TRANSLATE('A','1234567890','1111111111'), '1','YES', 'NO' ); Answer : NO Explanation : The query checks whether a given string is a numerical digit. 19. What does the following query do? SELECT SAL + NVL(COMM,0) FROM EMP; This displays the total salary of all employees. The null values in the commission column will be replaced by 0 and added to salary.

20. Which date function is used to find the difference between two dates? MONTHS_BETWEEN 21. Why does the following command give a compilation error? DROP TABLE &TABLE_NAME; Variable names should start with an alphabet. Here the table name starts with an '&' symbol. 22. What is the advantage of specifying WITH GRANT OPTION in the GRANT command? The privilege receiver can further grant the privileges he/she has obtained from the owner to any other user. 23. What is the use of the DROP option in the ALTER TABLE command? It is used to drop constraints specified on the table. 24. What is the value of ?comm? and ?sal? after executing the following query if the initial value of ?sal? is 10000? UPDATE EMP SET SAL = SAL + 1000, COMM = SAL*0.1; sal = 11000, comm = 1000 25. What is the use of DESC in SQL? Answer : DESC has two purposes. It is used to describe a schema as well as to retrieve rows from table in descending order. Explanation : The query SELECT * FROM EMP ORDER BY ENAME DESC will display the output sorted on ENAME in descending order. 26. What is the use of CASCADE CONSTRAINTS? When this clause is used with the DROP command, a parent table can be dropped even when a child table exists. 27. Which function is used to find the largest integer less than or equal to a specific value? FLOOR 28. What is the output of the following query? SELECT TRUNC(1234.5678,-2) FROM DUAL; 1200

SQL ? QUERIES I. SCHEMAS Table 1 : STUDIES PNAME (VARCHAR), SPLACE (VARCHAR), COURSE (VARCHAR), CCOST (NUMBER) Table 2 : SOFTWARE PNAME (VARCHAR), TITLE (VARCHAR), DEVIN (VARCHAR), SCOST (NUMBER), DCOST (NUMBER), SOLD (NUMBER) Table 3 : PROGRAMMER PNAME (VARCHAR), DOB (DATE), DOJ (DATE), SEX (CHAR), PROF1 (VARCHAR), PROF2 (VARCHAR), SAL (NUMBER) LEGEND : PNAME ? Programmer Name, SPLACE ? Study Place, CCOST ? Course Cost, DEVIN ? Developed in, SCOST ? Software Cost, DCOST ? Development Cost, PROF1 ? Proficiency 1 QUERIES : 1. Find out the selling cost average for packages developed in Oracle. 2. Display the names, ages and experience of all programmers. 3. Display the names of those who have done the PGDCA course. 4. What is the highest number of copies sold by a package? 5. Display the names and date of birth of all programmers born in April. 6. Display the lowest course fee. 7. How many programmers have done the DCA course. 8. How much revenue has been earned through the sale of packages developed in C. 9. Display the details of software developed by Rakesh. 10. How many programmers studied at Pentafour. 11. Display the details of packages whose sales crossed the 5000 mark. 12. Find out the number of copies which should be sold in order to recover the development cost of each package. 13. Display the details of packages for which the development cost has been recovered. 14. What is the price of costliest software developed in VB? 15. How many packages were developed in Oracle ? 16. How many programmers studied at PRAGATHI? 17. How many programmers paid 10000 to 15000 for the course? 18. What is the average course fee? 19. Display the details of programmers knowing C. 20. How many programmers know either C or Pascal?

21. How many programmers don?t know C and C++? 22. How old is the oldest male programmer? 23. What is the average age of female programmers? 24. Calculate the experience in years for each programmer and display along with their names in descending order. 25. Who are the programmers who celebrate their birthdays during the current month? 26. How many female programmers are there? 27. What are the languages known by the male programmers? 28. What is the average salary? 29. How many people draw 5000 to 7500? 30. Display the details of those who don?t know C, C++ or Pascal. 31. Display the costliest package developed by each programmer. 32. Produce the following output for all the male programmers Programmer Mr. Arvind ? has 15 years of experience KEYS: 1. SELECT AVG(SCOST) FROM SOFTWARE WHERE DEVIN = 'ORACLE'; 2. SELECT PNAME,TRUNC(MONTHS_BETWEEN(SYSDATE,DOB)/12) "AGE", TRUNC(MONTHS_BETWEEN(SYSDATE,DOJ)/12) "EXPERIENCE" FROM PROGRAMMER; 3. SELECT PNAME FROM STUDIES WHERE COURSE = 'PGDCA'; 4. SELECT MAX(SOLD) FROM SOFTWARE; 5. SELECT PNAME, DOB FROM PROGRAMMER WHERE DOB LIKE '%APR%'; 6. SELECT MIN(CCOST) FROM STUDIES; 7. SELECT COUNT(*) FROM STUDIES WHERE COURSE = 'DCA'; 8. SELECT SUM(SCOST*SOLD-DCOST) FROM SOFTWARE GROUP BY DEVIN HAVING DEVIN = 'C'; 9. SELECT * FROM SOFTWARE WHERE PNAME = 'RAKESH'; 10. SELECT * FROM STUDIES WHERE SPLACE = 'PENTAFOUR'; 11. SELECT * FROM SOFTWARE WHERE SCOST*SOLD-DCOST > 5000; 12. SELECT CEIL(DCOST/SCOST) FROM SOFTWARE; 13. SELECT * FROM SOFTWARE WHERE SCOST*SOLD >= DCOST; 14. SELECT MAX(SCOST) FROM SOFTWARE GROUP BY DEVIN HAVING DEVIN = 'VB'; 15. SELECT COUNT(*) FROM SOFTWARE WHERE DEVIN = 'ORACLE'; 16. SELECT COUNT(*) FROM STUDIES WHERE SPLACE = 'PRAGATHI'; 17. SELECT COUNT(*) FROM STUDIES WHERE CCOST BETWEEN 10000 AND 15000; 18. SELECT AVG(CCOST) FROM STUDIES; 19. SELECT * FROM PROGRAMMER WHERE PROF1 = 'C' OR PROF2 = 'C'; 20. SELECT * FROM PROGRAMMER WHERE PROF1 IN ('C','PASCAL') OR PROF2 IN ('C','PASCAL'); 21. SELECT * FROM PROGRAMMER WHERE PROF1 NOT IN ('C','C++') AND PROF2 NOT IN ('C','C++'); 22. SELECT TRUNC(MAX(MONTHS_BETWEEN(SYSDATE,DOB)/12)) FROM PROGRAMMER WHERE SEX = 'M'; 23. SELECT TRUNC(AVG(MONTHS_BETWEEN(SYSDATE,DOB)/12)) FROM PROGRAMMER WHERE SEX = 'F'; 24. SELECT PNAME, TRUNC(MONTHS_BETWEEN(SYSDATE,DOJ)/12) FROM PROGRAMMER ORDER BY PNAME DESC; 25. SELECT PNAME FROM PROGRAMMER WHERE TO_CHAR(DOB,'MON') = TO_CHAR(SYSDATE,'MON'); 26. SELECT COUNT(*) FROM PROGRAMMER WHERE SEX = 'F'; 27. SELECT DISTINCT(PROF1) FROM PROGRAMMER WHERE SEX = 'M'; 28. SELECT AVG(SAL) FROM PROGRAMMER; 29. SELECT COUNT(*) FROM PROGRAMMER WHERE SAL BETWEEN 5000 AND 7500;

30. SELECT * FROM PROGRAMMER WHERE PROF1 NOT IN ('C','C++','PASCAL') AND PROF2 NOT IN ('C','C++','PASCAL'); 31. SELECT PNAME,TITLE,SCOST FROM SOFTWARE WHERE SCOST IN (SELECT MAX(SCOST) FROM SOFTWARE GROUP BY PNAME); 32.SELECT 'Mr.' || PNAME || ' - has ' || TRUNC(MONTHS_BETWEEN(SYSDATE,DOJ)/12) || ' years of experience' ?Programmer? FROM PROGRAMMER WHERE SEX = 'M' UNION SELECT 'Ms.' || PNAME || ' - has ' || TRUNC (MONTHS_BETWEEN (SYSDATE,DOJ)/12) || ' years of experience' ?Programmer? FROM PROGRAMMER WHERE SEX = 'F';

II . SCHEMA : Table 1 : DEPT DEPTNO (NOT NULL , NUMBER(2)), DNAME (VARCHAR2(14)), LOC (VARCHAR2(13) Table 2 : EMP EMPNO (NOT NULL , NUMBER(4)), ENAME (VARCHAR2(10)), JOB (VARCHAR2(9)), MGR (NUMBER(4)), HIREDATE (DATE), SAL (NUMBER(7,2)), COMM (NUMBER(7,2)), DEPTNO (NUMBER(2)) MGR is the empno of the employee whom the employee reports to. DEPTNO is a foreign key. QUERIES 1. List all the employees who have at least one person reporting to them. 2. List the employee details if and only if more than 10 employees are present in department no 10. 3. List the name of the employees with their immediate higher authority. 4. List all the employees who do not manage any one. 5. List the employee details whose salary is greater than the lowest salary of an employee belonging to deptno 20. 6. List the details of the employee earning more than the highest paid manager. 7. List the highest salary paid for each job. 8. Find the most recently hired employee in each department. 9. In which year did most people join the company? Display the year and the number of employees. 10. Which department has the highest annual remuneration bill? 11. Write a query to display a ?*? against the row of the most recently hired employee. 12. Write a correlated sub-query to list out the employees who earn more than the average salary of their department. 13. Find the nth maximum salary. 14. Select the duplicate records (Records, which are inserted, that already exist) in the EMP table. 15. Write a query to list the length of service of the employees (of the form n years and m months). KEYS: 1. SELECT DISTINCT(A.ENAME) FROM EMP A, EMP B WHERE A.EMPNO = B.MGR; or SELECT ENAME FROM EMP WHERE EMPNO IN (SELECT MGR FROM EMP);

2. SELECT * FROM EMP WHERE DEPTNO IN (SELECT DEPTNO FROM EMP GROUP BY DEPTNO HAVING COUNT(EMPNO)>10 AND DEPTNO=10); 3. SELECT A.ENAME "EMPLOYEE", B.ENAME "REPORTS TO" FROM EMP A, EMP B WHERE A.MGR=B.EMPNO; 4. SELECT * FROM EMP WHERE EMPNO IN ( SELECT EMPNO FROM EMP MINUS SELECT MGR FROM EMP); 5. SELECT * FROM EMP WHERE SAL > ( SELECT MIN(SAL) FROM EMP GROUP BY DEPTNO HAVING DEPTNO=20); 6. SELECT * FROM EMP WHERE SAL > ( SELECT MAX(SAL) FROM EMP GROUP BY JOB HAVING JOB = 'MANAGER' ); 7. SELECT JOB, MAX(SAL) FROM EMP GROUP BY JOB; 8. SELECT * FROM EMP WHERE (DEPTNO, HIREDATE) IN (SELECT DEPTNO, MAX(HIREDATE) FROM EMP GROUP BY DEPTNO); 9. SELECT TO_CHAR(HIREDATE,'YYYY') "YEAR", COUNT(EMPNO) "NO. OF EMPLOYEES" FROM EMP GROUP BY TO_CHAR(HIREDATE,'YYYY') HAVING COUNT(EMPNO) = (SELECT MAX(COUNT(EMPNO)) FROM EMP GROUP BY TO_CHAR(HIREDATE,'YYYY')); 10. SELECT DEPTNO, LPAD(SUM(12*(SAL+NVL(COMM,0))),15) "COMPENSATION" FROM EMP GROUP BY DEPTNO HAVING SUM( 12*(SAL+NVL(COMM,0))) = (SELECT MAX(SUM(12*(SAL+NVL(COMM,0)))) FROM EMP GROUP BY DEPTNO); 11. SELECT ENAME, HIREDATE, LPAD('*',8) "RECENTLY HIRED" FROM EMP WHERE HIREDATE = (SELECT MAX(HIREDATE) FROM EMP) UNION SELECT ENAME NAME, HIREDATE, LPAD(' ',15) "RECENTLY HIRED" FROM EMP WHERE HIREDATE != (SELECT MAX(HIREDATE) FROM EMP); 12. SELECT ENAME,SAL FROM EMP E WHERE SAL > (SELECT AVG(SAL) FROM EMP F WHERE E.DEPTNO = F.DEPTNO); 13. SELECT ENAME, SAL FROM EMP A WHERE &N = (SELECT COUNT (DISTINCT(SAL)) FROM EMP B WHERE A.SAL<=B.SAL); 14. SELECT * FROM EMP A WHERE A.EMPNO IN (SELECT EMPNO FROM EMP GROUP BY EMPNO HAVING COUNT(EMPNO)>1) AND A.ROWID!=MIN (ROWID)); 15. SELECT ENAME "EMPLOYEE",TO_CHAR(TRUNC(MONTHS_BETWEEN(SYSDATE,HIREDATE)/12))||' YEARS '|| TO_CHAR(TRUNC(MOD(MONTHS_BETWEEN (SYSDATE, HIREDATE),12)))||' MONTHS ' "LENGTH OF SERVICE" FROM EMP;

Question: What are the wildcards used for pattern matching. Answer: _ for single character substitution and % for multi -character substitution. Question: How can I hide a particular table name of our schema? Answer: you can hide the table name by creating synonyms. e.g) you can create a synonym y for table x create synonym y for x; Question: When we give SELECT * FROM EMP; How does oracle respond: Answer: When u give SELECT * FROM EMP; the server check all the data in the EMP file and it displays the data of the EMP file Question: What is the use of CASCADE CONSTRAINTS? Answer: When this clause is used with the DROP command, a parent table can be dropped even when a child table exists. Question: There are 2 tables, Employee and Department. There are few records in employee table, for which, the

department is not assigned. The output of the query should contain all th employees names and their corresponding departments, if the department is assigned otherwise employee names and null value in the place department name. What is the query? Answer: What you want to use here is called a left outer join with Employee table on the left side. A left outer join as the name says picks up all the records from the left table and based on the joint column picks the matching records from the right table and in case there are no matching records in the right table, it shows null for the selected columns of the right table. E.g. in this query which uses the key-word LEFT OUTER JOIN. Syntax though varies across databases. In DB2/UDB it uses the key word LEFT OUTER JOIN, in case of Oracle the connector is Employee_table.Dept_id *= Dept_table.Dept_id SQL Server/Sybase : Employee_table.Dept_id(+) = Dept_table.Dept_id Question: on index why u need indexing? Where that is stored and what u mean by schema object? For what purpose we are using view Answer: We can?t create an Index on Index. Index is stored in user_index table. Every object that has been created on Schema is Schema Object like Table, View etc. If we want to share the particular data to various users we have to use the virtual table for the Base table...So that is a view. Question: How to store directory structure in a database? Answer: We can do it by the following command: create or replace directory as 'c: \tmp' Question: Why does the following command give a compilation error? DROP TABLE &TABLE_NAME; Answer: Variable names should start with an alphabet. Here the table name starts with an '&' symbol. Question: Difference between VARCHAR and VARCHAR2? Answer: Varchar means fixed length character data (size) i.e., min size-1 and max-2000 Varchar2 means variable length character data i.e., min -1 to max-4000 Question: Which command displays the SQL command in the SQL buffer, and then executes it Answer: You set the LIST or L command to get the recent one from SQL Buffer Question: Which system table contains information on constraints on all the tables created? Answer: USER_CONSTRAINTS. Question: How do I write a program which will run a SQL query and mail the results to a group? Answer: Use DBMS_JOB for scheduling a program job and DBMS_MAIL to send the results through email. Question: There is an Eno. & gender in a table. Eno. has primary key and gender has a check constraints for the values 'M' and 'F'. While inserting the data into the table M was misspelled as F and F as M. What is the update? Answer: update <TableName> set gender= case where gender='F' Then 'M'

where gender='M' Then 'F' Question: What the difference between UNION and UNIONALL? Answer: union will return the distinct rows in two select s, while union all return all rows. Question: How can we backup the sql files & what is SAP? Answer: You can backup the sql files through backup utilities or some backup command in sql. SAP is ERP software for the organization to integrate the software. Question: What is the difference between TRUNCATE and DELETE commands? Answer: TRUNCATE is a DDL command whereas DELETE is a DML command. Hence DELETE operation can be rolled back, but TRUNCATE operation cannot be rolled back. WHERE clause can be used with DELETE and not with TRUNCATE. Question: State true or false. !=, <>, ^= all denote the same operation. Answer: True. Question: State true or false. EXISTS, SOME, ANY are operators in SQL. Answer: True. Question: What will be the output of the following query? SELECT REPLACE (TRANSLATE (LTRIM (RTRIM ('!! ATHEN!!','!'), '!'), 'AN', '**'),'*','TROUBLE') FROM DUAL; Answer: TROUBLETHETROUBLE. Question: What is the advantage to use trigger in your PL? Answer: Triggers are fired implicitly on the tables/views on which they are created. There are various advantages of using a trigger. Some of them are: - Suppose we need to validate a DML statement (insert/Update/Delete) that modifies a table then we can write a trigger on the table that gets fired implicitly whenever DML statement is executed on that table. - Another reason of using triggers can be for automatic updation of one or more tables whenever a DML/DDL statement is executed for the table on which the trigger is created. - Triggers can be used to enforce constraints. For eg: Any insert/update/ Delete statements should not be allowed on a particular table after office hours. For enforcing this constraint Triggers should be used. - Triggers can be used to publish information about database events to subscribers. Database event can be a system event like Database startup or shutdown or it can be a user even like User login in or user logoff. Question: How write a SQL statement to query the result set and display row as columns and columns as row? Answer: TRANSFORM Count (Roll_no) AS Count of Roll_no SELECT Academic_Status FROM tbl_enr_status GROUP BY Academic_Status PIVOT Curnt_status; Question: Cursor Syntax brief history

Answer: To retrieve data with SQL one row at a time you need to use cursor processing. Not all relational databases support this, but many do. Here I show this in Oracle with PL/SQL, which is Procedural Language SQL .Cursor processing is done in several steps:1. Define the rows you want to retrieve. This is called declaring the cursor.2. Open the cursor. This activates the cursor and loads the data. Note that declaring the cursor doesn't load data, opening the cursor does.3. Fetch the data into variables.4. Close the cursor. Question: What is the data type of the surrogate key? Answer: Data type of the surrogate key is either integer or numeric or number

Question: How to write a sql statement to find the first occurrence of a non zero value? Answer: There is a slight chance the column "a" has a value of 0 which is not null. In that case, you?ll loose the information. There is another way of searching the first not null value of a column: select column_name from table_name where column_name is not null and rownum<2; Question: What is normalazation, types with e.g.\'s. _ with queries of all types Answer: There are 5 normal forms. It is necessary for any database to be in the third normal form to maintain referential integrity and non-redundancy. First Normal Form: Every field of a table (row, col) must contain an atomic value Second Normal Form: All columns of a table must depend entirely on the primary key column. Third Normal Form: All columns of a table must depend on all columns of a composite primary key. Fourth Normal Form: A table must not contain two or more independent multi -valued facts. This normal form is often avoided for maintenance reasons. Fifth Normal Form: is about symmetric dependencies. Each normal form assumes that the table is already in the earlier normal form. Question: Given an unnormalized table with columns: Answer: The query will be: delete from tabname where rowid not in (select max (rowid) from tabname group by name) Here tabname is the table name. Question: How to find second maximum value from a table? Answer: select max (field1) from tname1 where field1= (select max (field1) from tname1 where field1<(select max(field1) from tname1); Field1- Salary field Tname= Table name. Question: What is the advantage of specifying WITH GRANT OPTION in the GRANT command? Answer: The privilege receiver can further grant the privileges he/she has obtained from the owner to any other user. Question: What is the main difference between the IN and EXISTS clause in sub queries?? Answer: The main difference between the IN and EXISTS predicate in sub query is the way in which the query gets executed. IN -- The inner query is executed first and the list of values obtained as its result is used by the outer query. The

inner query is executed for only once. EXISTS -- The first row from the outer query is selected, then the inner query is executed and, the outer query output uses this result for checking. This process of inner query execution repeats as many no .of times as there are outer query rows. That is, if there are ten rows that can result from outer query, the inner query is executed that many no. of times.

Question: TRUNCATE TABLE EMP; DELETE FROM EMP; Will the outputs of the above two commands differ Answer: The difference is that the TRUNCATE call cannot be rolled back and all memory space for that table is released back to the server. TRUNCATE is much faster than DELETE and in both cases only the table data is removed, not the table structure. Question: What is table space? Answer: Table-space is a physical concept. It has pages where the records of the database are stored with a logical perception of tables. So table space contains tables. Question: How to find out the 10th highest salary in SQL query? Answer: Table - Tbl_Test_Salary Column - int_salary select max (int_salary) from Tbl_Test_Salary where int_salary in (select top 10 int_Salary from Tbl_Test_Salary order by int_salary) Question: Which command executes the contents of a specified file? Answer: START <filename> or @<filename>. Question: What is the difference between SQL and SQL SERVER? Answer: SQL Server is an RDBMS just like oracle, DB2 from Microsoft whereas Structured Query Language (SQL), pronounced "sequel", is a language that provides an interface to relational database systems. It was developed by IBM in the 1970s for use in System R. SQL is a de facto standard, as well as an ISO and ANSI standard. SQL is used to perform various operations on RDBMS. Question: What is the difference between Single row sub-Query and Scalar Sub-Query? Answer: SINGLE ROW SUBQUERY RETURNS A VALUE WHICH IS USED BY WHERE CLAUSE, WHEREAS SCALAR SUBQUERY IS A SELECT STATEMENT USED IN COLUMN LIST CAN BE THOUGHT OF AS AN INLINE FUNCTION IN SELECT COLUMN LIST. Question: What does the following query do? Answer: SELECT SAL + NVL (COMM, 0) FROM EMP; It gives the added value of sal and comm for each employee in the emp table. NVL (null value) replaces null with 0.

Question: How to find second maximum value from a table? Answer: select max (field1) from tname1 where field1= (select max (field1) from tname1 where field1< (select max (field1) from tname1); Field1- Salary field Tname= Table name. Question: I have a table with duplicate names in it. Write me a query which returns only duplicate rows with number of times they are repeated. Answer: SELECT COL1 FROM TAB1 WHERE COL1 IN (SELECT MAX (COL1) FROM TAB1 GROUP BY COL1 HAVING COUNT (COL1) > 1) Question: How to find out the database name from SQL*PLUS command prompt? Answer: Select * from global_name; This will give the data base name which u r currently connected to..... Question: How to display duplicate rows in a table? Answer: select * from emp group by (empid) having count (empid)>1 Question: What is the value of comm and sal after executing the following query if the initial value of ?sal? is 10000 UPDATE EMP SET SAL = SAL + 1000, COMM = SAL*0.1; Answer: sal = 11000, comm = 1000. Question: 1) What is difference between Oracle and MS Access? 2) What are disadvantages in Oracle and MS Access? 2) What are features & advantages in Oracle and MS Access? Answer: Oracle's features for distributed transactions, materialized views and replication are not available with MS Access. These features enable Oracle to efficiently store data for multinational companies across the globe. Also these features increase scalability of applications based on Oracle.

What is JServer and what is it used for? Oracle JServer Option is a Java Virtual Machine (Java VM) which runs within the Oracle database server?s address space. Oracle also provides a JServer Accelerator to compile Java code natively. This speeds up the execution of Java code by eliminating interpreter overhead.

How does one install the Oracle JServer Option?Follow these steps to activate the Oracle JServer/ JVM option: Make sure your database is started with large java_pool_size (>20M) and shared_pool_size (>50M) INIT.ORA parameter values. Run the $ORACLE_HOME/javavm/install/initjvm.sql script from SYS AS SYSDBA to install the Oracle JServer Option on a database. Grant JAVAUSERPRIV to users that wants to use Java: SQL> GRANT JAVAUSERPRIV TO SCOTT;

The rmjvm.sql script can be used to deinstall the JServer option from your database. Follow the steps in the Oracle Migrations Guide to upgrade or downgrade the JServer option from one release to another. ce code into the database? Use the |CREATE OR REPLACE JAVA SOURCE| command or |loadjava| utility. Loaded code can be viewed by selecting from the USER_SOURCE view.

Why does one need to publish Java in the database? Publishing Java classes on the database makes it visible on a SQL and PL/SQL level. It is important to publish your code before calling it from SQL statements or PL/SQL code. What is JDBC and what is it used for? JDBC is a set of classes and interfaces written in Java to allow other Java programs to send SQL statements to a relational database management system. Oracle provides three categories of JDBC drivers: (a) JDBC Thin Driver (No local Net8 installation required/ handy for applets), (b) JDBC OCI for writing stand-alone Java applications, (c) JDBC KPRB driver (default connection) for Java Stored Procedures and Database JSP?s.

How does one connect with the JDBC Thin Driver? The the JDBC thin driver provides the only way to access Oracle from the Web (applets). It is smaller and faster than the OCI drivers, and doesn?t require a pre-installed version of the JDBC drivers. import java.sql.*;class dbAccess , public static void main (String args *+) throws SQLException , DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver()); Connection conn = DriverManager.getConnection (|jdbc:oracle:thin:@hostname:1526:orcl|, |scott|, |tiger|); // @machineName:port:SID, userid, password Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery(|select BANNER from SYS.V_$VERSION|); while (rset.next()) System.out.println (rset.getString(1)); // Print col 1 stmt.close(); --How does one connect with the JDBC OCI Driver? One must have Net8 (SQL*Net) installed and working before attempting to use one of the OCI drivers. import java.sql.*;class dbAccess , public static void main (String args *+) throws SQLException , try , Class.forName (|oracle.jdbc.driver.OracleDriver|); - catch (ClassNotFoundException e) , e.printStackTrace(); - Connection conn = DriverManager.getConnection (|jdbc:oracle:oci8:@hostname_orcl|, |scott|, |tiger|); // or oci7 @TNSNames_Entry, userid, password Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery(|select BANNER from SYS.V_$VERSION|); while (rset.next()) System.out.println (rset.getString(1)); // Print col 1 stmt.close(); --How does one connect with the JDBC KPRB Driver? One can obtain a handle to the default or current connection (KPRB driver) by calling the OracleDriver.defaultConenction() method. Please note that you do not need to specify a database URL, username or password as you are already connected to a database session. Remember not to close the default connection. Closing the default connection might throw an exception in future releases of Oracle. import java.sql.*;class dbAccess , public static void main (String args *+) throws SQLException , Connection conn = (new oracle.jdbc.driver.OracleDriver()).defaultConnection(); Statement stmt = conn.createStatement(); ResultSet rset = stmt.executeQuery(|select BANNER from SYS.V_$VERSION|); while (rset.next()) System.out.println (rset.getString(1)); // Print col 1 stmt.close(); --What is SQLJ and what is it used for? SQLJ is an ANSI standard way of coding SQL access in Java. It provides a Java precompiler that translates SQLJ call to JDBC calls. The idea is similar to that of other Oracle Precompilers. How does one deploy SQLJ programs? Use the sqlj compiler to compile your *.sqlj files to *.java and *.ser files. The *.ser files contain vendor specific database code. Thereafter one invokes the javac compiler to compile the .java files to *.class files. The *.class and *.ser files needs to be deployed.

What is JDeveloper and what is it used for? JDeveloper is the Oracle IDE (Integrated Development Environment) for developing SQLJ and JDBC programs, applets, stored procedures, EJB?s, JSP?s etc. What is InfoBus DAC and what is it used for? InfoBus DAC (Data Aware Controls) is a standard Java extension used in JDeveloper to create data aware forms. It replaced the JBCL interface that were used in JDeveloper V1 and V2. What is a JSP and what is it used for? Java Server Pages (JSP) is a platform independent presentation layer technology that comes with SUN?s J2EE platform. JSPs are normal HTML pages with Java code pieces embedded in them. JSP pages are saved to *.jsp files. A JSP compiler is used in the background to generate a Servlet from the JSP page.

What is the difference between ASP and JSP? Active Server Pages (ASP) is a Microsoft standard, which is easier to develop than Java Server Pages (JSP). However ASP is a proprietary technology and is less flexible than JSP. For more information about ASP, see the Oracle ASP FAQ.

How does one invoke a JSP? A JSP gets invoked when you call a *.jsp file from your Web Server like you would call a normal *.html file. Obviously your web server need to support JSP pages and must be configured properly to handle them.

How does a JSP gets executed? The first time you call a JSP, a servlet (*.java) will be created and compiled to a .class file. The class file is then executed on the server. Output produced by the servlet is returned to the web browser. Output will typically be HTML or XML code.

What is a Java Stored Procedure/ Trigger? A Java Stored Procedure is a procedure coded in Java (as opposed to PL/SQL) and stored in the Oracle database. Java Stored procedures are executed by the database JVM in database memory space. Java Stored Procedures can be developed in JDBC or SQLJ. Interfacing between PL/SQL and Java are extremely easy. Please note that Java Stored procedures are by default executed with invokers rights. PL/SQL procedures are by default executed with defines rights.

How does one see the uptime for a database? (for DBA ) Look at the following SQL query: SELECT to_char (startup_time,'DD-MON-YYYY HH24: MI: SS') "DB Startup Time" FROM sys.v_$instance; Marco Bergman provided the following alternative solution: SELECT to_char (logon_time,'Dy dd Mon HH24: MI: SS') "DB Startup Time" FROM sys.v_$session WHERE Sid=1 /* this is pmon */ / Users still running on Oracle 7 can try one of the following queries: Column STARTED format a18 head 'STARTUP TIME' Select C.INSTANCE, to_date (JUL.VALUE, 'J') || to_char (floor (SEC.VALUE/3600), '09') || ':' -- || Substr (to_char (mod (SEC.VALUE/60, 60), '09'), 2, 2) || Substr (to_char (floor (mod (SEC.VALUE/60, 60)), '09'), 2, 2)

|| '.' || Substr (to_char (mod (SEC.VALUE, 60), '09'), 2, 2) STARTED from SYS.V_$INSTANCE JUL, SYS.V_$INSTANCE SEC, SYS.V_$THREAD C Where JUL.KEY like '%JULIAN%' and SEC.KEY like '%SECOND%'; Select to_date (JUL.VALUE, 'J') || to_char (to_date (SEC.VALUE, 'SSSSS'), ' HH24:MI:SS') STARTED from SYS.V_$INSTANCE JUL, SYS.V_$INSTANCE SEC where JUL.KEY like '%JULIAN%' and SEC.KEY like '%SECOND%'; select to_char (to_date (JUL.VALUE, 'J') + (SEC.VALUE/86400), -Return a DATE 'DD-MON-YY HH24:MI:SS') STARTED from V$INSTANCE JUL, V$INSTANCE SEC where JUL.KEY like '%JULIAN%' and SEC.KEY like '%SECOND%'; Where are my TEMPFILES, I don't see them in V$DATAFILE or DBA_DATA_FILE? (for DBA) Tempfiles, unlike normal datafiles, are not listed in v$datafile or dba_data_files. Instead query v$tempfile or dba_temp_files: SELECT * FROM v$tempfile; SELECT * FROM dba_temp_files; How do I find used/free space in a TEMPORARY tablespace? (for DBA ) Unlike normal tablespaces, true temporary tablespace information is not listed in DBA_FREE_SPACE. Instead use the V$TEMP_SPACE_HEADER view: SELECT tablespace_name, SUM (bytes used), SUM (bytes free) FROM V$temp_space_header GROUP BY tablespace_name; What is a profile ? Each database user is assigned a Profile that specifies limitations on various system resources available to the user. How will you enforce security using stored procedures? Don't grant user access directly to tables within the application. Instead grant the ability to access the procedures that access the tables. When procedure executed it will execute the privilege of procedures owner. Users cannot access tables except via the procedure. How can one see who is using a temporary segment? (for DBA ) For every user using temporary space, there is an entry in SYS.V$_LOCK with type 'TS'. All temporary segments are named 'ffff.bbbb' where 'ffff' is the file it is in and 'bbbb' is first block of the segment. If your temporary tablespace is set to TEMPORARY, all sorts are done in one large temporary segment. For usage stats, see SYS.V_$SORT_SEGMENT From Oracle 8.0, one can just query SYS.v$sort_usage. Look at these examples: select s.username, u."USER", u.tablespace, u.contents, u.extents, u.blocks from sys.v_$session s, sys.v_$sort_usage u

where s.addr = u.session_addr / select s.osuser, s.process, s.username, s.serial#, Sum (u.blocks)*vp.value/1024 sort_size from sys.v_$session s, sys.v_$sort_usage u, sys.v_$parameter VP where s.saddr = u.session_addr and vp.name = 'db_block_size' and s.osuser like '&1' group by s.osuser, s.process, s.username, s.serial#, vp.value / How does one get the view definition of fixed views/tables? Query v$fixed_view_definition. Example: SELECT * FROM v$fixed_view_definition WHERE view_name='V$SESSION'; What are the dictionary tables used to monitor a database spaces ? DBA_FREE_SPACE DBA_SEGMENTS DBA_DATA_FILES. How can we specify the Archived log file name format and destination? By setting the following values in init.ora file. LOG_ARCHIVE_FORMAT = arch %S/s/T/tarc (%S - Log sequence number and is zero left paded, %s - Log sequence number not padded. %T - Thread number lef-zero-paded and %t Thread number not padded). The file name created is arch 0001 are if %S is used. LOG_ARCHIVE_DEST = path. What is user Account in Oracle database? An user account is not a physical structure in Database but it is having important relationship to the objects in the database and will be having certain privileges. When will the data in the snapshot log be used? We must be able to create a after row trigger on table (i.e., it should be not be already available) After giving table privileges. We cannot specify snapshot log name because oracle uses the name of the master table in the name of the database objects that support its snapshot log. The master table name should be less than or equal to 23 characters. (The table name created will be MLOGS_tablename, and trigger name will be TLOGS name). What dynamic data replication? Updating or Inserting records in remote database through database triggers. It may fail if remote database is having any problem. What is Two-Phase Commit ? Two-phase commit is mechanism that guarantees a distributed transaction either commits on all involved nodes or rolls back on all involved nodes to maintain data consistency across the global distributed database. It has two phase, a Prepare Phase and a Commit Phase. How can you Enforce Referential Integrity in snapshots ? Time the references to occur when master tables are not in use. Peform the reference the manually immdiately locking the master tables. We can join tables in snopshots by creating a complex snapshots that will based on the master tables.

What is a SQL * NET? SQL *NET is ORACLE's mechanism for interfacing with the communication protocols used by the networks that facilitate distributed processing and distributed databases. It is used in Clint -Server and Server-Server communications. What is a SNAPSHOT ? Snapshots are read-only copies of a master table located on a remote node which is periodically refreshed to reflect changes made to the master table. What is the mechanism provided by ORACLE for table replication ? Snapshots and SNAPSHOT LOGs What is snapshots? Snapshot is an object used to dynamically replicate data between distribute database at specified time intervals. In ver 7.0 they are read only. What are the various type of snapshots? Simple and Complex. Describe two phases of Two-phase commit ? Prepare phase - The global coordinator (initiating node) ask a participants to prepare (to promise to commit or rollback the transaction, even if there is a failure) Commit - Phase - If all participants respond to the coordinator that they are prepared, the coordinator asks all nodes to commit the transaction, if all participants cannot prepare, the coordinator asks all nodes to roll back the transaction. What is snapshot log ? It is a table that maintains a record of modifications to the master table in a snapshot. It is stored in the same database as master table and is only available for simple snapshots. It should be created before creating snapshots. What are the benefits of distributed options in databases? Database on other servers can be updated and those transactions can be grouped together with others in a logical unit. Database uses a two phase commit. What are the options available to refresh snapshots ? COMPLETE - Tables are completely regenerated using the snapshots query and the master tables every time the snapshot referenced. FAST - If simple snapshot used then a snapshot log can be used to send the changes to the snapshot tables. FORCE - Default value. If possible it performs a FAST refresh; Otherwise it will perform a complete refresh. What is a SNAPSHOT LOG ? A snapshot log is a table in the master database that is associated with the master table. ORACLE uses a snapshot log to track the rows that have been updated in the master table. Snapshot logs are used in updating the snapshots based on the master table. What is Distributed database ? A distributed database is a network of databases managed by multiple database servers that appears to a user as single logical database. The data of all databases in the distributed database can be simultaneously accessed and modified.

How can we reduce the network traffic? - Replication of data in distributed environment. - Using snapshots to replicate data. - Using remote procedure calls. Differentiate simple and complex, snapshots ? - A simple snapshot is based on a query that does not contains GROUP BY clauses, CONNECT BY clauses, JOINs, sub query or snashot of operations. - A complex snapshots contain atleast any one of the above. What are the Built-ins used for sending Parameters to forms? You can pass parameter values to a form when an application executes the call_form, New_form, Open_form or Run_product. Can you have more than one content canvas view attached with a window? Yes. Each window you create must have atleast one content canvas view assigned to it. You can also create a window that has manipulated content canvas view. At run time only one of the content canvas views assign to a window is displayed at a time. Is the After report trigger fired if the report execution fails? Yes. Does a Before form trigger fire when the parameter form is suppressed? Yes. What is SGA? The System Global Area in an Oracle database is the area in memory to facilitate the transfer of information between users. It holds the most recently requested structural information between users. It holds the most recently requested structural information about the database. The structure is database buffers, dictionary cache, redo log buffer and shared pool area. What is a shared pool? The data dictionary cache is stored in an area in SGA called the shared pool. This will allow sharing of parsed SQL statements among concurrent users. What is mean by Program Global Area (PGA)? It is area in memory that is used by a single Oracle user process. What is a data segment? Data segment are the physical areas within a database block in which the data associated with tables and clusters are stored. What are the factors causing the reparsing of SQL statements in SGA? Due to insufficient shared pool size. Monitor the ratio of the reloads takes place while executing SQL statements. If the ratio is greater than 1 then increase the SHARED_POOL_SIZE. What are clusters?

Clusters are groups of one or more tables physically stores together to share common columns and are often used together. What is cluster key? The related columns of the tables in a cluster are called the cluster key. Do a view contain data? Views do not contain or store data. What is user Account in Oracle database? A user account is not a physical structure in database but it is having important relationship to the objects in the database and will be having certain privileges. How will you enforce security using stored procedures? Don't grant user access directly to tables within the application. Instead grant the ability to access the procedures that access the tables. When procedure executed it will execute the privilege of procedures owner. Users cannot access tables except via the procedure. What are the dictionary tables used to monitor a database space? DBA_FREE_SPACE DBA_SEGMENTS DBA_DATA_FILES. Can a property clause itself be based on a property clause? Yes If a parameter is used in a query without being previously defined, what diff. exist between. report 2.0 and 2.5 when the query is applied? While both reports 2.0 and 2.5 create the parameter, report 2.5 gives a message that a bind parameter has been created. What are the sql clauses supported in the link property sheet? Where start with having. What is trigger associated with the timer? When-timer-expired. What are the trigger associated with image items? When-image-activated fires when the operators double clicks on an image itemwhen -image-pressed fires when an operator clicks or double clicks on an image item What are the different windows events activated at runtimes? When_window_activated When_window_closed When_window_deactivated When_window_resized Within this triggers, you can examine the built in system variable system. event_window to determine the name of the window for which the trigger fired.

When do you use data parameter type? When the value of a data parameter being passed to a called product is always the name of the record group defined in the current form. Data parameters are used to pass data to products invoked with the run_product built in subprogram. What is difference between open_form and call_form? when one form invokes another form by executing open_form the first form remains displayed, and operators can navigate between the forms as desired. when one form invokes another form by executing call_form, the called form is modal with respect to the calling form. That is, any windows that belong to the calling form are disabled, and operators cannot navigate to them until they first exit the called form. What is new_form built-in? When one form invokes another form by executing new_form oracle form exits the first form and releases its memory before loading the new form calling new form completely replace the first with the second. If there are changes pending in the first form, the operator will be prompted to save them before the new form is loaded. What is the "LOV of Validation" Property of an item? What is the use of it? When LOV for Validation is set to True, Oracle Forms compares the current value of the text item to the values in the first column displayed in the LOV. Whenever the validation event occurs. If the value in the text item matches one of the values in the first column of the LOV, validation succeeds, the LOV is not displayed, and processing continues normally. If the value in the text item does not match one of the values in the first column of the LOV, Oracle Forms displays the LOV and uses the text item value as the search criteria to automatically reduce the list. What is the diff. when Flex mode is mode on and when it is off? When flex mode is on, reports automatically resizes the parent when the child is resized. What is the diff. when confine mode is on and when it is off? When confine mode is on, an object cannot be moved outside its parent in the layout. What are visual attributes? Visual attributes are the font, color, pattern proprieties that you set for form and menu objects that appear in your application interface. Which of the two views should objects according to possession? view by structure. What are the two types of views available in the object navigator(specific to report 2.5)? View by structure and view by type . What are the vbx controls? Vbx control provide a simple method of building and enhancing user interfaces. The controls can use to obtain user inputs and display program outputs.vbx control where originally develop as extensions for the ms visual basic environments and include such items as sliders, rides and knobs. What is the use of transactional triggers? Using transactional triggers we can control or modify the default functionality of the oracle forms. How do you create a new session while open a new form? Using open_form built-in setting the session option Ex. Open_form('Stocks ',active, session). when invoke the

multiple forms with open form and call_form in the same application, state whether the following are true/False What are the ways to monitor the performance of the report? Use reports profile executable statement. Use SQL trace facility. If two groups are not linked in the data model editor, What is the hierarchy between them? Two group that is above are the left most rank higher than the group that is to right or below it. An open form can not be execute the call_form procedure if you chain of called forms has been initiated by another open form? True Explain about horizontal, Vertical tool bar canvas views? Tool bar canvas views are used to create tool bars for individual windows. Horizontal tool bars are display at the top of a window, just under its menu bar. Vertical Tool bars are displayed along the left side of a window What is the purpose of the product order option in the column property sheet? To specify the order of individual group evaluation in a cross products. What is the use of image_zoom built-in? To manipulate images in image items. How do you reference a parameter indirectly? To indirectly reference a parameter use the NAME IN, COPY 'built-ins to indirectly set and reference the parameters value' Example name_in ('capital parameter my param'), Copy ('SURESH','Parameter my_param') What is a timer? Timer is an "internal time clock" that you can programmatically create to perform an action each time the times. What are the two phases of block coordination? There are two phases of block coordination: the clear phase and the population phase. During, the clear phase, Oracle Forms navigates internally to the detail block and flushes the obsolete detail records. During the population phase, Oracle Forms issues a SELECT statement to repopulate the detail block with detail records associated with the new master record. These operations are accomplished through the execution of triggers. What are Most Common types of Complex master -detail relationships? There are three most common types of complex master -detail relationships: master with dependent details master with independent details detail with two masters What is a text list? The text list style list item appears as a rectangular box which displays the fixed number of values. When the text list contains values that can not be displayed, a vertical scroll bar appears, allowing the operator to view and select undisplayed values. What is term? The term is terminal definition file that describes the terminal form which you are using r20run.

What is use of term? The term file which key is correspond to which oracle report functions. What is pop list? The pop list style list item appears initially as a single field (similar to a text item field). When the operator selects the list icon, a list of available choices appears. What is the maximum no of chars the parameter can store? The maximum no of chars the parameter can store is only valid for char parameters, which can be upto 64K. No parameters default to 23Bytes and Date parameter default to 7Bytes. What are the default extensions of the files created by library module? The default file extensions indicate the library module type and storage format .pll - pl/sql library module binary What are the Coordination Properties in a Master -Detail relationship? The coordination properties are Deferred Auto-Query These Properties determine when the population phase of block coordination should occur. How do you display console on a window ? The console includes the status line and message line, and is displayed at the bottom of the window to which it is assigned.To specify that the console should be displayed, set the console window form property to the name of any window in the form. To include the console, set console window to Null. What are the different Parameter types? Text ParametersData Parameters State any three mouse events system variables? System.mouse_button_pressedSystem.mouse_button_shift What are the types of calculated columns available? Summary, Formula, Placeholder column. Explain about stacked canvas views? Stacked canvas view is displayed in a window on top of, or "stacked" on the content canvas view assigned to that same window. Stacked canvas views obscure some part of the underlying content canvas view, and or often shown and hidden programmatically. How does one do off-line database backups? (for DBA ) Shut down the database from sqlplus or server manager. Backup all files to secondary storage (eg. tapes). Ensure that you backup all data files, all control files and all log files. When completed, restart your database. Do the following queries to get a list of all files that needs to be backed up: select name from sys.v_$datafile; select member from sys.v_$logfile; select name from sys.v_$controlfile; Sometimes Oracle takes forever to shutdown with the "immediate" option. As workaround to this problem, shutdown using these commands:

alter system checkpoint; shutdown abort startup restrict shutdown immediate Note that if you database is in ARCHIVELOG mode, one can still use archived log files to roll forward from an off -line backup. If you cannot take your database down for a cold (off-line) backup at a convenient time, switch your database into ARCHIVELOG mode and perform hot (on-line) backups. What is the difference between SHOW_EDITOR and EDIT_TEXTITEM? Show editor is the generic built-in which accepts any editor name and takes some input string and returns modified output string. Whereas the edit_textitem built-in needs the input focus to be in the text item before the built -in is executed. What are the built-ins that are used to Attach an LOV programmatically to an item? set_item_property get_item_property (by setting the LOV_NAME property) How does one do on-line database backups? (for DBA ) Each tablespace that needs to be backed-up must be switched into backup mode before copying the files out to secondary storage (tapes). Look at this simple example. ALTER TABLESPACE xyz BEGIN BACKUP; ! cp xyfFile1 /backupDir/ ALTER TABLESPACE xyz END BACKUP; It is better to backup tablespace for tablespace than to put all tablespaces in backup mode. Backing them up separately incurs less overhead. When done, remember to backup your control files. Look at this example: ALTER SYSTEM SWITCH LOGFILE; -- Force log switch to update control file headers ALTER DATABASE BACKUP CONTROLFILE TO '/backupDir/control.dbf'; NOTE: Do not run on-line backups during peak processing periods. Oracle will write complete database blocks instead of the normal deltas to redo log files while in backup mode. This will lead to excessive database archiving and even database freezes. How does one backup a database using RMAN? (for DBA ) The biggest advantage of RMAN is that it only backup used space in the database. Rman doesn't put tablespaces in backup mode, saving on redo generation overhead. RMAN will re -read database blocks until it gets a consistent image of it. Look at this simple backup example. rman target sys/*** nocatalog run , allocate channel t1 type disk; backup format '/app/oracle/db_backup/%d_t%t_s%s_p%p' ( database ); release channel t1; Example RMAN restore: rman target sys/*** nocatalog run , allocate channel t1 type disk; # set until time 'Aug 07 2000 :51';

restore tablespace users; recover tablespace users; release channel t1; The examples above are extremely simplistic and only useful for illustrating basic concepts. By default Oracle uses the database controlfiles to store information about backups. Normally one would rather setup a RMAN catalog database to store RMAN metadata in. Read the Oracle Backup and Recovery Guide before implementing any RMAN backups. Note: RMAN cannot write image copies directly to tape. One needs to use a third -party media manager that integrates with RMAN to backup directly to tape. Alternatively one can backup to disk and then manually copy the backups to tape. What are the different file extensions that are created by oracle reports? Rep file and Rdf file. What is strip sources generate options? Removes the source code from the library file and generates a library files that contains only pcode. The resulting file can be used for final deployment, but can not be subsequently edited in the designer.ex. f45gen module=old_lib.pll userid=scott/tiger strip_source YES output_file How does one put a database into ARCHIVELOG mode? (for DBA ) The main reason for running in archivelog mode is that one can provide 24 -hour availability and guarantee complete data recoverability. It is also necessary to enable ARCHIVELOG mode before one can start to use on -line database backups. To enable ARCHIVELOG mode, simply change your database startup command script, and bounce the database: SQLPLUS> connect sys as sysdba SQLPLUS> startup mount exclusive; SQLPLUS> alter database archivelog; SQLPLUS> archive log start; SQLPLUS> alter database open; NOTE1: Remember to take a baseline database backup right after enabling archivelog mode. Without it one would not be able to recover. Also, implement an archivelog backup to prevent the archive log directory from filling -up. NOTE2: ARCHIVELOG mode was introduced with Oracle V6, and is essential for database point-in-time recovery. Archiving can be used in combination with on-line and off-line database backups. NOTE3: You may want to set the following INIT.ORA parameters when enabling ARCHIVELOG mode: log_archive_start=TRUE, log_archive_dest=... and log_archive_format=... NOTE4: You can change the archive log destination of a database on-line with the ARCHIVE LOG START TO 'directory'; statement. This statement is often used to switch archiving between a set of directories. NOTE5: When running Oracle Real Application Server (RAC), you need to shut down all nodes before changing the database to ARCHIVELOG mode. What is the basic data structure that is required for creating an LOV? Record Group. How does one backup archived log files? (for DBA ) One can backup archived log files using RMAN or any operating system backup utility. Remember to delete files after backing them up to prevent the archive log directory from filling up. If the archive log directory becomes full, your database will hang! Look at this simple RMAN backup script: RMAN> run ,

2> allocate channel dev1 type disk; 3> backup 4> format '/app/oracle/arch_backup/log_t%t_s%s_p%p' 5> (archivelog all delete input); 6> release channel dev1; 7> Does Oracle write to data files in begin/hot backup mode? (for DBA ) Oracle will stop updating file headers, but will continue to write data to the database files even if a tablespace is in backup mode. In backup mode, Oracle will write out complete changed blocks to the redo log files. Normally only deltas (changes) are logged to the redo logs. This is done to enable reconstruction of a block if only half of it was backed up (split blocks). Because of this, one should notice increased log activity and archiving during on -line backups.

What is the Maximum allowed length of Record group Column? Record group column names cannot exceed 30 characters. Which parameter can be used to set read level consistency across multiple queries? Read only What are the different types of Record Groups? Query Record Groups NonQuery Record Groups State Record Groups From which designation is it preferred to send the output to the printed? Previewer What are difference between post database commit and post -form commit? Post-form commit fires once during the post and commit transactions process, after the database commit occurs. The post-form-commit trigger fires after inserts, updates and deletes have been posted to the database but before the transactions have been finalized in the issuing the command. The post-database-commit trigger fires after oracle forms issues the commit to finalized transactions. What are the different display styles of list items? Pop_listText_listCombo box Which of the above methods is the faster method? performing the calculation in the query is faster. With which function of summary item is the compute at options required? percentage of total functions. What are parameters? Parameters provide a simple mechanism for defining and setting the valuesof inputs that are required by a form at startup. Form parameters are variables of type char,number,date that you define at design time. What are the three types of user exits available ?

Oracle Precompiler exits, Oracle call interface, NonOracle user exits. How many windows in a form can have console? Only one window in a form can display the console, and you cannot change the console assignment at runtime. What is an administrative (privileged) user? (for DBA ) Oracle DBAs and operators typically use administrative accounts to manage the database and database instance. An administrative account is a user that is granted SYSOPER or SYSDBA privileges. SYSDBA and SYSOPER allow access to a database instance even if it is not running. Control of these privileges is managed outside of the database via password files and special operating system groups. This password file is created with the orapwd utility. What are the two repeating frame always associated with matrix object? One down repeating frame below one across repeating frame. What are the master-detail triggers? On-Check_delete_masterOn_clear_detailsOn_populate_details How does one connect to an administrative user? (for DBA ) If an administrative user belongs to the "dba" group on Unix, or the "ORA_DBA" (ORA_sid_DBA) group on NT, he/she can connect like this: connect / as sysdba No password is required. This is equivalent to the desupported "connect internal" method. A password is required for "non-secure" administrative access. These passwords are stored in password files. Remote connections via Net8 are classified as non-secure. Look at this example: connect sys/password as sysdba How does one create a password file? (for DBA ) The Oracle Password File ($ORACLE_HOME/dbs/orapw or orapwSID) stores passwords for users with administrative privileges. One needs to create a password files before remote administrators (like OEM) will be allowed to connect. Follow this procedure to create a new password file: . Log in as the Oracle software owner . Runcommand: orapwd file=$ORACLE_HOME/dbs/orapw$ORACLE_SID password=mypasswd . Shutdown the database (SQLPLUS> SHUTDOWN IMMEDIATE) . Edit the INIT.ORA file and ensure REMOTE_LOGIN_PASSWORDFILE=exclusive is set. . Startup the database (SQLPLUS> STARTUP) NOTE: The orapwd utility presents a security risk in that it receives a password from the command line. This password is visible in the process table of many systems. Administrators needs to be aware of this! Is it possible to modify an external query in a report which contains it? No. Does a grouping done for objects in the layout editor affect the grouping done in the data model editor? No. How does one add users to a password file? (for DBA ) One can select from the SYS.V_$PWFILE_USERS view to see which users are listed in the password file. New users can be added to the password file by granting them SYSDBA or SYSOPER privileges, or by using the orapwd utility.

GRANT SYSDBA TO scott; If a break order is set on a column would it affect columns which are under the column? No Why are OPS$ accounts a security risk in a client/server environment? (for DBA ) If you allow people to log in with OPS$ accounts from Windows Workstations, you cannot be sure who they really are. With terminals, you can rely on operating system passwords, with Windows, you cannot. If you set REMOTE_OS_AUTHENT=TRUE in your init.ora file, Oracle assumes that the remote OS has authenticated the user. If REMOTE_OS_AUTHENT is set to FALSE (recommended), remote users will be unable to connect without a password. IDENTIFIED EXTERNALLY will only be in effect from the local host. Also, if you are using "OPS$" as your prefix, you will be able to log on locally with or without a password, regardless of whether you have identified your ID with a password or defined it to be IDENTIFIED EXTERNALLY. Do user parameters appear in the data modal editor in 2.5? No Can you pass data parameters to forms? No Is it possible to link two groups inside a cross products after the cross products group has been created? no What are the different modals of windows? Modalless windows Modal windows What are modal windows? Modal windows are usually used as dialogs, and have restricted functionality compared to modelless windows. On some platforms for example operators cannot resize, scroll or iconify a modal window. What are the different default triggers created when Master Deletes Property is set to Non -isolated? Master Deletes Property Resulting Triggers ---------------------------------------------------Non-Isolated(the default) On-Check-Delete-Master On-Clear-Details On-Populate-Details What are the different default triggers created when Master Deletes Property is set to isolated? Master Deletes Property Resulting Triggers --------------------------------------------------Isolated On-Clear-Details On-Populate-Details What are the different default triggers created when Master Deletes Property is set to Cascade? Master Deletes Property Resulting Triggers

--------------------------------------------------Cascading On-Clear-Details On-Populate-Details Pre-delete What is the diff. bet. setting up of parameters in reports 2.0 reports2.5? LOVs can be attached to parameters in the reports 2.5 parameter form. What are the difference between lov & list item? Lov is a property where as list item is an item. A list item can have only one column, lov can have one or more columns What is the advantage of the library? Libraries provide a convenient means of storing client-side program units and sharing them among multiple applications. Once you create a library, you can attach it to any other form, menu, or library modules. When you can call library program units from triggers menu items commands and user named routine, you write in the modules to which you have attach the library. When a library attaches another library, program units in the first library can reference program units in the attached library. Library support dynamic loading -that is library program units are loaded into an application only when needed. This can significantly reduce the run -time memory requirements of applications. What is lexical reference? How can it be created? Lexical reference is place_holder for text that can be embedded in a sql statements. A lexical reference can be created using & before the column or parameter name. What is system.coordination_operation? It represents the coordination causing event that occur on the master block in master -detail relation. What is synchronize? It is a terminal screen with the internal state of the form. It updates the screen display to reflect the information that oracle forms has in its internal representation of the screen. What use of command line parameter cmd file? It is a command line argument that allows you to specify a file that contain a set of arguments for r20run. What is a Text_io Package? It allows you to read and write information to a file in the file system. What is forms_DDL? Issues dynamic Sql statements at run time, including server side pl/SQl and DDL How is link tool operation different bet. reports 2 & 2.5? In Reports 2.0 the link tool has to be selected and then two fields to be linked are selected and the link is automatically created. In 2.5 the first field is selected and the link tool is then used to link the first field to the second field. What are the different styles of activation of ole Objects? In place activationExternal activation

How do you reference a Parameter? In Pl/Sql, You can reference and set the values of form parameters using bind variables syntax. Ex. PARAMETER name = '' or :block.item = PARAMETER Parameter name What is the difference between object embedding & linking in Oracle forms? In Oracle forms, Embedded objects become part of the form module, and linked objects are references from a form module to a linked source file. Name of the functions used to get/set canvas properties? Get_view_property, Set_view_property What are the built-ins that are used for setting the LOV properties at runtime? get_lov_property set_lov_property What are the built-ins used for processing rows? Get_group_row_count(function) Get_group_selection_count(function) Get_group_selection(function) Reset_group_selection(procedure) Set_group_selection(procedure) Unset_group_selection(procedure) What are built-ins used for Processing rows? GET_GROUP_ROW_COUNT(function) GET_GROUP_SELECTION_COUNT(function) GET_GROUP_SELECTION(function) RESET_GROUP_SELECTION(procedure) SET_GROUP_SELECTION(procedure) UNSET_GROUP_SELECTION(procedure) What are the built-in used for getting cell values? Get_group_char_cell(function) Get_groupcell(function) Get_group_number_cell(function) What are the built-ins used for Getting cell values? GET_GROUP_CHAR_CELL (function) GET_GROUPCELL(function) GET_GROUP_NUMBET_CELL(function) Atleast how many set of data must a data model have before a data model can be base on it? Four To execute row from being displayed that still use column in the row which property can be used? Format trigger. What are different types of modules available in oracle form? Form module - a collection of objects and code routines Menu modules - a collection of menus and menu item

commands that together make up an application menu library module - a collection of user named procedures, functions and packages that can be called from other modules in the application What is the remove on exit property? For a modelless window, it determines whether oracle forms hides the window automatically when the operators navigates to an item in the another window. What is WHEN-Database-record trigger? Fires when oracle forms first marks a record as an insert or an update. The trigger fires as soon as oracle forms determines through validation that the record should be processed by the next post or commit as an insert or update. c generally occurs only when the operators modifies the first item in the record, and after the operator attempts to navigate out of the item. What is a difference between pre-select and pre-query? Fires during the execute query and count query processing after oracle forms constructs the select statement to be issued, but before the statement is actually issued. The pre -query trigger fires just before oracle forms issues the select statement to the database after the operator as define the example records by entering the query criteria in enter query mode.Pre-query trigger fires before pre-select trigger. What are built-ins associated with timers? find_timercreate_timerdelete_timer What are the built-ins used for finding object ID functions? Find_group(function) Find_column(function) What are the built-ins used for finding Object ID function? FIND_GROUP(function) FIND_COLUMN(function) Any attempt to navigate programmatically to disabled form in a call_form stack is allowed? False Use the Add_group_row procedure to add a row to a static record group 1. true or false? False What third party tools can be used with Oracle EBU/ RMAN? (for DBA) The following Media Management Software Vendors have integrated their media management software packages with Oracle Recovery Manager and Oracle7 Enterprise Backup Utility. The Media Management Vendors will provide first line technical support for the integrated backup/recover solutions. Veritas NetBackup EMC Data Manager (EDM) HP OMNIBack II IBM's Tivoli Storage Manager - formerly ADSM Legato Networker ManageIT Backup and Recovery Sterling Software's SAMS:Alexandria - formerly from Spectralogic Sun Solstice Backup

Why and when should one tune? (for DBA) One of the biggest responsibilities of a DBA is to ensure that the Oracle database is tuned properly. The Oracle RDBMS is highly tunable and allows the database to be monitored and adjusted to increase its performance. One should do performance tuning for the following reasons: The speed of computing might be wasting valuable human time (users waiting for response); Enable your system to keep-up with the speed business is conducted; and Optimize hardware usage to save money (companies are spending millions on hardware). Although this FAQ is not overly concerned with hardware issues, one needs to remember than you cannot tune a Buick into a Ferrari. How can a break order be created on a column in an existing group? What are the various sub events a mouse double click event involves? By dragging the column outside the group. What is the use of place holder column? What are the various sub events a mouse double click event involves? A placeholder column is used to hold calculated values at a specified place rather than allowing is to appear in the actual row where it has to appear. What is the use of hidden column? What are the various sub events a mouse double click event involves? A hidden column is used to when a column has to embed into boilerplate text. What database aspects should be monitored? (for DBA) One should implement a monitoring system to constantly monitor the following aspects of a database. Writing custom scripts, implementing Oracle's Enterprise Manager, or buying a third-party monitoring product can achieve this. If an alarm is triggered, the system should automatically notify the DBA (e -mail, page, etc.) to take appropriate action. Infrastructure availability: . Is the database up and responding to requests . Are the listeners up and responding to requests . Are the Oracle Names and LDAP Servers up and responding to requests . Are the Web Listeners up and responding to requests Things that can cause service outages: . Is the archive log destination filling up? . Objects getting close to their max extents . User and process limits reached Things that can cause bad performance: See question "What tuning indicators can one use?". Where should the tuning effort be directed? (for DBA) Consider the following areas for tuning. The order in which steps are listed needs to be maintained to prevent tuning side effects. For example, it is no good increasing the buffer cache if you can reduce I/O by rewriting a SQL statement. Database Design (if it's not too late): Poor system performance usually results from a poor database design. One should generally normalize to the 3NF. Selective denormalization can provide valuable performance improvements. When designing, always keep the "data access path" in mind. Also look at proper data partitioning, data replication, aggregation tables for decision support systems, etc. Application Tuning: Experience showed that approximately 80% of all Oracle system performance problems are resolved by coding

optimal SQL. Also consider proper scheduling of batch tasks after peak working hours. Memory Tuning: Properly size your database buffers (shared pool, buffer cache, log buffer, etc) by looking at your buffer hit ratios. Pin large objects into memory to prevent frequent reloads. Disk I/O Tuning: Database files needs to be properly sized and placed to provide maximum disk subsystem throughput. Also look for frequent disk sorts, full table scans, missing indexes, row chaining, data fragmentation, etc Eliminate Database Contention: Study database locks, latches and wait events carefully and eliminate where possible. Tune the Operating System: Monitor and tune operating system CPU, I/O and memory utilization. For more information, read the related Oracle FAQ dealing with your specific operating system. What are the various sub events a mouse double click event involves? What are the various sub events a mouse double click event involves? Double clicking the mouse consists of the mouse down, mouse up, mouse click, mouse down & mouse up events. What are the default parameter that appear at run time in the parameter screen? What are the various sub events a mouse double click event involves? Destype and Desname. What are the built-ins used for Creating and deleting groups? CREATE-GROUP (function) CREATE_GROUP_FROM_QUERY(function) DELETE_GROUP(procedure) What are different types of canvas views? Content canvas views Stacked canvas views Horizontal toolbar vertical toolbar. What are the different types of Delete details we can establish in Master -Details? Cascade Isolate Non-isolate What is relation between the window and canvas views? Canvas views are the back ground objects on which you place the interface items (Text items), check boxes, radio groups etc.,) and boilerplate objects (boxes, lines, images etc.,) that operators interact with us they run your form . Each canvas views displayed in a window. What is a User_exit? Calls the user exit named in the user_exit_string. Invokes a 3Gl program by name which has been properly linked into your current oracle forms executable. How is it possible to select generate a select set for the query in the query property sheet? By using the tables/columns button and then specifying the table and the column names. How can values be passed bet. precompiler exits & Oracle call interface?

By using the statement EXECIAFGET & EXECIAFPUT. How can a square be drawn in the layout editor of the report writer? By using the rectangle tool while pressing the (Constraint) key. How can a text file be attached to a report while creating in the report writer? By using the link file property in the layout boiler plate property sheet. How can I message to passed to the user from reports? By using SRW.MESSAGE function. Does one need to drop/ truncate objects before importing? (for DBA) Before one import rows into already populated tables, one needs to truncate or drop these tables to get rid of the old data. If not, the new data will be appended to the existing tables. One must always DROP existing Sequences before re-importing. If the sequences are not dropped, they will generate numbers inconsistent with the rest of the database. Note: It is also advisable to drop indexes before importing to speed up the import process. Indexes can easily be recreated after the data was successfully imported. How can a button be used in a report to give a drill down facility? By setting the action associated with button to Execute pl/sql option and using the SRW.Run_report function. Can one import/export between different versions of Oracle? (for DBA) Different versions of the import utility is upwards compatible. This means that one can take an export file created from an old export version, and import it using a later version of the import utility. This is quite an effective way of upgrading a database from one release of Oracle to the next. Oracle also ships some previous catexpX.sql scripts that can be executed as user SYS enabling older imp/exp versions to work (for backwards compatibility). For example, one can run $ORACLE_HOME/rdbms/admin/catexp7.sql on an Oracle 8 database to allow the Oracle 7.3 exp/imp utilities to run against an Oracle 8 database. What are different types of images? Boiler plate imagesImage Items Can one export to multiple files?/ Can one beat the Unix 2 Gig limit? (for DBA) From Oracle8i, the export utility supports multiple output files. This feature enables large exports to be divided into files whose sizes will not exceed any operating system limits (FILESIZE= parameter). When importing from multi -file export you must provide the same filenames in the same sequence in the FILE= parameter. Look at this example: exp SCOTT/TIGER FILE=D:\F1.dmp,E:\F2.dmp FILESIZE=10m LOG=scott.log Use the following technique if you use an Oracle version prior to 8i: Create a compressed export on the fly. Depending on the type of data, you probably can export up to 10 gigabytes to a single file. This example uses gzip. It offers the best compression I know of, but you can also substitute it with zip, compress or whatever. # create a named pipe mknod exp.pipe p # read the pipe - output to zip file in the background gzip <> scott.exp.gz & # feed the pipe exp userid=scott/tiger file=exp.pipe ...

What is bind reference and how can it be created? Bind reference are used to replace the single value in sql, pl/sql statements a bind reference can be created using a (:) before a column or a parameter name. How can one improve Import/ Export performance? (for DBA) EXPORT: . Set the BUFFER parameter to a high value (e.g. 2M) . Set the RECORDLENGTH parameter to a high value (e.g. 64K) . Stop unnecessary applications to free-up resources for your job. . If you run multiple export sessions, ensure they write to different physical disks. . DO NOT export to an NFS mounted filesystem. It will take forever. IMPORT: . Create an indexfile so that you can create indexes AFTER you have imported data. Do this by setting INDEXFILE to a filename and then import. No data will be imported but a file containing index definitions will be created. You must edit this file afterwards and supply the passwords for the schemas on all CONNECT statements. . Place the file to be imported on a separate physical disk from the oracle data files . Increase DB_CACHE_SIZE (DB_BLOCK_BUFFERS prior to 9i) considerably in the init$SID.ora file . Set the LOG_BUFFER to a big value and restart oracle. . Stop redo log archiving if it is running (ALTER DATABASE NOARCHIVELOG;) . Create a BIG tablespace with a BIG rollback segment inside. Set all other rollback segments offline (except the SYSTEM rollback segment of course). The rollback segment must be as big as your biggest table (I think?) . Use COMMIT=N in the import parameter file if you can afford it . Use ANALYZE=N in the import parameter file to avoid time consuming ANALYZE statements . Remember to run the indexfile previously created Give the sequence of execution of the various report triggers? Before form , After form , Before report, Between page, After report. What are the common Import/ Export problems? (for DBA ) ORA-00001: Unique constraint (...) violated - You are importing duplicate rows. Use IGNORE=NO to skip tables that already exist (imp will give an error if the object is re-created). ORA-01555: Snapshot too old - Ask your users to STOP working while you are exporting or use parameter CONSISTENT=NO ORA-01562: Failed to extend rollback segment - Create bigger rollback segments or set parameter COMMIT=Y while importing IMP-00015: Statement failed ... object already exists... - Use the IGNORE=Y import parameter to ignore these errors, but be careful as you might end up with duplicate rows. Why is it preferable to create a fewer no. of queries in the data model? Because for each query, report has to open a separate cursor and has to rebind, execute and fetch data.

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

What is coordination Event? Any event that makes a different record in the master block the current record is a coordination causing event. What is the difference between OLE Server & Ole Container? An Ole server application creates ole Objects that are embedded or linked in ole Containers ex. Ole servers are ms_word & ms_excel. OLE containers provide a place to store, display and manipulate objects that are created by ole server applications. Ex. oracle forms is an example of an ole Container. What is an object group? An object group is a container for a group of objects; you define an object group when you want to package related objects, so that you copy or reference them in other modules. What is an LOV? An LOV is a scrollable popup window that provides the operator with either a single or multi column selection list. At what point of report execution is the before Report trigger fired? After the query is executed but before the report is executed and the records are displayed. What are the built -ins used for Modifying a groups structure? ADD-GROUP_COLUMN (function) ADD_GROUP_ROW (procedure) DELETE_GROUP_ROW(procedure) What is an user exit used for? A way in which to pass control (and possibly arguments ) form Oracle report to another Oracle products of 3 GL and then return control ( and ) back to Oracle reports. What is the User-Named Editor? A user named editor has the same text editing functionality as the default editor, but, because it is a named object, you can specify editor attributes such as windows display size, position, and title. My database was terminated while in BACKUP MODE, do I need to recover? (for DBA) If a database was terminated while one of its tablespaces was in BACKUP MODE (ALTER TABLESPACE xyz BEGIN BACKUP;), it will tell you that media recovery is required when you try to restart the database. The DBA is then required to recover the database and apply all archived logs to the database. However, from Oracle7.2, you can simply take the individual datafiles out of backup mode and restart the database. ALTER DATABASE DATAFILE '/path/filename' END BACKUP; One can select from V$BACKUP to see which datafiles are in backup mode. This normally saves a significant amount of database down time. Thiru Vadivelu contributed the following: From Oracle9i onwards, the following command can be used to take all of the datafiles out of hot backup mode: ALTER DATABASE END BACKUP; The above commands need to be issued when the database is mounted. What is a Static Record Group? A static record group is not associated with a query, rather, you define its structure and row values at design time, and they remain fixed at runtime. What is a record group?

A record group is an internal Oracle Forms that structure that has a column/row framework similar to a database table. However, unlike database tables, record groups are separate objects that belong to the form module which they are defined. My database is down and I cannot restore. What now? (for DBA ) Recovery without any backup is normally not supported, however, Oracle Consulting can sometimes extract data from an offline database using a utility called DUL (Disk UnLoad). This utility reads data in the data files and unloads it into SQL*Loader or export dump files. DUL does not care about rollback segments, corrupted blocks, etc, and can thus not guarantee that the data is not logically corrupt. It is intended as an absolute last resort and will most likely cost your company a lot of money!!! I've lost my REDOLOG files, how can I get my DB back? (for DBA) The following INIT.ORA parameter may be required if your current redo logs are corrupted or blown away. Caution is advised when enabling this parameter as you might end-up losing your entire database. Please contact Oracle Support before using it. _allow_resetlogs_corruption = true What is a property clause? A property clause is a named object that contains a list of properties and their settings. Once you create a property clause you can base other object on it. An object based on a property can inherit the setting of any property in the clause that makes sense for that object. What is a physical page ? & What is a logical page ? A physical page is a size of a page. That is output by the printer. The logical page is the size of one page of the actual report as seen in the Previewer. I've lost some Rollback Segments, how can I get my DB back? (for DBA) Re-start your database with the following INIT.ORA parameter if one of your rollback segments is corrupted. You can then drop the corrupted rollback segments and create it from scratch. Caution is advised when enabling this parameter, as uncommitted transactions will be marked as committed. One can very well end up with lost or inconsistent data!!! Please contact Oracle Support before using it. _Corrupted_rollback_segments = (rbs01, rbs01, rbs03, rbs04) What are the differences between EBU and RMAN? (for DBA) Enterprise Backup Utility (EBU) is a functionally rich, high performance interface for backing up Oracle7 databases. It is sometimes referred to as OEBU for Oracle Enterprise Backup Utility. The Oracle Recovery Manager (RMAN) utility that ships with Oracle8 and above is similar to Oracle7's EBU utility. However, there is no direct upgrade path from EBU to RMAN. How does one create a RMAN recovery catalog? (for DBA) Start by creating a database schema (usually called rman). Assign an appropriate tablespace to it and grant it the recovery_catalog_owner role. Look at this example: sqlplus sys SQL>create user rman identified by rman; SQL> alter user rman default tablespace tools temporary tablespace temp; SQL> alter user rman quota unlimited on tools; SQL> grant connect, resource, recovery_catalog_owner to rman; SQL> exit; Next, log in to rman and create the catalog schema. Prior to Oracle 8i this was done by running the catrman.sql script. rman catalog rman/rman

RMAN>create catalog tablespace tools; RMAN> exit; You can now continue by registering your databases in the catalog. Look at this example: rman catalog rman/rman target backdba/backdba RMAN> register database; How can a group in a cross products be visually distinguished from a group that does not form a cross product? A group that forms part of a cross product will have a thicker border. What is the frame & repeating frame? A frame is a holder for a group of fields. A repeating frame is used to display a set of records when the no. of records that are to displayed is not known before. What is a combo box? A combo box style list item combines the features found in list and text item. Unlike the pop list or the text list style list items, the combo box style list item will both display fixed values and accept one operator entered value. What are three panes that appear in the run time pl/sql interpreter? 1. Source pane. 2. interpreter pane. 3. Navigator pane. What are the two panes that Appear in the design time pl/sql interpreter? 1. Source pane. 2. Interpreter pane What are the two ways by which data can be generated for a parameters list of values? 1. Using static values. 2. Writing select statement. What are the various methods of performing a calculation in a report ? 1. Perform the calculation in the SQL statements itself. 2. Use a calculated / summary column in the data model. What are the default extensions of the files created by menu module? .mmb, .mmx What are the default extensions of the files created by forms modules? .fmb - form module binary .fmx - form module executable To display the page no. for each page on a report what would be the source & logical page no. or & of physical page no.? & physical page no. It is possible to use raw devices as data files and what is the advantages over file. system files ? Yes. The advantages over file system files. I/O will be improved because Oracle is bye -passing the kernnel which writing into disk. Disk Corruption will be very less.

What are disadvantages of having raw devices ? We should depend on export/import utility for backup/recovery (fully reliable) The tar command cannot be used for physical file backup, instead we can use dd command which is less flexible and has limited recoveries. What is the significance of having storage clause ? We can plan the storage for a table as how much initial extents are required, how much can be extended next, how much % should leave free for managing row updations etc., What is the use of INCTYPE option in EXP command ? Type export should be performed COMPLETE,CUMULATIVE,INCREMENTAL. List the sequence of events when a large transaction that exceeds beyond its optimal value when an entry wraps and causes the rollback segment toexpand into anotion Completes. e. will be written. What is the use of FILE option in IMP command ? The name of the file from which import should be performed. What is a Shared SQL pool? The data dictionary cache is stored in an area in SGA called the Shared SQL Pool. This will allow sharing of parsed SQL statements among concurrent users. What is hot backup and how it can be taken? Taking backup of archive log files when database is open. For this the ARCHIVELOG mode should be enabled. The following files need to be backed up. All data files. All Archive log, redo log files. All control files. List the Optional Flexible Architecture (OFA) of Oracle database? or How can we organize the tablespaces in Oracle database to have maximum performance ? SYSTEM - Data dictionary tables. DATA - Standard operational tables. DATA2- Static tables used for standard operations INDEXES - Indexes for Standard operational tables. INDEXES1 - Indexes of static tables used for standard operations. TOOLS - Tools table. TOOLS1 - Indexes for tools table. RBS - Standard Operations Rollback Segments, RBS1,RBS2 - Additional/Special Rollback segments. TEMP - Temporary purpose tablespace TEMP_USER - Temporary tablespace for users. USERS - User tablespace. How to implement the multiple control files for an existing database ? Shutdown the database Copy one of the existing control file to new location Edit Config ora file by adding new control file. name Restart the database. What is advantage of having disk shadowing/ Mirroring ? Shadow set of disks save as a backup in the event of disk failure. In most Operating System if any disk failure occurs it automatically switchover to place of failed disk. Improved performance because most OS support volume shadowing can direct file I/O request to use the shadow set of files instead of the main set of files. This reduces I/O load on the main set of disks.

How will you force database to use particular rollback segment ? SET TRANSACTION USE ROLLBACK SEGMENT rbs_name. Why query fails sometimes ? Rollback segment dynamically extent to handle larger transactions entry loads. A single transaction may wipeout all available free space in the Rollback Segment Tablespace. This prevents other user using Rollback segments. What is the use of RECORD LENGTH option in EXP command ? Record length in bytes. How will you monitor rollback segment status ? Querying the DBA_ROLLBACK_SEGS view IN USE - Rollback Segment is on-line. AVAILABLE - Rollback Segment available but not on-line. OFF-LINE - Rollback Segment off-line INVALID - Rollback Segment Dropped. NEEDS RECOVERY - Contains data but need recovery or corupted. PARTLY AVAILABLE - Contains data from an unresolved transaction involving a distributed database. What is meant by Redo Log file mirroring ? How it can be achieved? Process of having a copy of redo log files is called mirroring. This can be achieved by creating group of log files together, so that LGWR will automatically writes them to all the members of the current on -line redo log group. If any one group fails then database automatically switch over to next group. It degrades performance. Which parameter in Storage clause will reduce no. of rows per block? PCTFREE parameter Row size also reduces no of rows per block. What is meant by recursive hints ? Number of times processes repeatedly query the dictionary table is called recursive hints. It is due to the data dictionary cache is too small. By increasing the SHARED_POOL_SIZE parameter we can optimize the size of Data Dictionary Cache. What is the use of PARFILE option in EXP command ? Name of the parameter file to be passed for export. What is the difference between locks, latches, enqueues and semaphores? (for DBA) A latch is an internal Oracle mechanism used to protect data structures in the SGA from simultaneous access. Atomic hardware instructions like TEST-AND-SET is used to implement latches. Latches are more restrictive than locks in that they are always exclusive. Latches are never queued, but will spin or sleep until they obtain a resource, or time out. Enqueues and locks are different names for the same thing. Both support queuing and concurrency. They are queued and serviced in a first-in-first-out (FIFO) order. Semaphores are an operating system facility used to control waiting. Semaphores are controlled by the following Unix parameters: semmni, semmns and semmsl. Typical settings are: semmns = sum of the "processes" parameter for each instance (see init.ora for each instance) semmni = number of instances running simultaneously;

semmsl = semmns What is a logical backup? Logical backup involves reading a set of database records and writing them into a file. Export utility is used for taking backup and Import utility is used to recover from backup. Where can one get a list of all hidden Oracle parameters? (for DBA) Oracle initialization or INIT.ORA parameters with an underscore in front are hidden or unsupported parameters. One can get a list of all hidden parameters by executing this query: select * from SYS.X$KSPPI where substr(KSPPINM,1,1) = '_'; The following query displays parameter names with their current value: select a.ksppinm "Parameter", b.ksppstvl "Session Value", c.ksppstvl "Instance Value" from x$ksppi a, x$ksppcv b, x$ksppsv c where a.indx = b.indx and a.indx = c.indx and substr(ksppinm,1,1)='_' order by a.ksppinm; Remember: Thou shall not play with undocumented parameters! What is a database EVENT and how does one set it? (for DBA) Oracle trace events are useful for debugging the Oracle database server. The following two examples are simply to demonstrate syntax. Refer to later notes on this page for an explanation of what these particular events do. Either adding them to the INIT.ORA parameter file can activate events. E.g. event='1401 trace name errorstack, level 12' ... or, by issuing an ALTER SESSION SET EVENTS command: E.g. alter session set events '10046 trace name context forever, level 4'; The alter session method only affects the user's current session, whereas changes to the INIT.ORA file will affect all sessions once the database has been restarted. What is a Rollback segment entry ? It is the set of before image data blocks that contain rows that are modified by a transaction. Each Rollback Segment entry must be completed within one rollback segment. A single rollback segment can have multiple rollback segment entries. What database events can be set? (for DBA) The following events are frequently used by DBAs and Oracle Support to diagnose problems: " 10046 trace name context forever, level 4 Trace SQL statements and show bind variables in trace output. " 10046 trace name context forever, level 8 This shows wait events in the SQL trace files " 10046 trace name context forever, level 12 This shows both bind variable names and wait events in the SQL trace files " 1401 trace name errorstack, level 12 1401 trace name errorstack, level 4 1401 trace name processstate Dumps out trace information if an ORA-1401 "inserted value too large for column" error occurs. The 1401 can be replaced by any other Oracle Server error code that you want to trace. " 60 trace name errorstack level 10 Show where in the code Oracle gets a deadlock (ORA-60), and may help to diagnose the problem. The following lists of events are examples only. They might be version specific, so please call Oracle before using them: " 10210 trace name context forever, level 10 10211 trace name context forever, level 10 10231 trace name context

forever, level 10 These events prevent database block corruptions " 10049 trace name context forever, level 2 Memory protect cursor " 10210 trace name context forever, level 2 Data block check " 10211 trace name context forever, level 2 Index block check " 10235 trace name context forever, level 1 Memory heap check " 10262 trace name context forever, level 300 Allow 300 bytes memory leak for connections Note: You can use the Unix oerr command to get the description of an event. On Unix, you can type "oerr ora 10053" from the command prompt to get event details. How can one dump internal database structures? (for DBA) The following (mostly undocumented) commands can be used to obtain information about internal database structures. o Dump control file contents alter session set events 'immediate trace name CONTROLF level 10' / o Dump file headers alter session set events 'immediate trace name FILE_HDRS level 10' / o Dump redo log headers alter session set events 'immediate trace name REDOHDR level 10' / o Dump the system state NOTE: Take 3 successive SYSTEMSTATE dumps, with 10-minute intervals alter session set events 'immediate trace name SYSTEMSTATE level 10' / o Dump the process state alter session set events 'immediate trace name PROCESSSTATE level 10' / o Dump Library Cache details alter session set events 'immediate trace name library cache level 10' / o Dump optimizer statistics whenever a SQL statement is parsed (hint: change statement or flush pool) alter session set events '10053 trace name context forever, level 1' / o Dump a database block (File/ Block must be converted to DBA address) Convert file and block number to a DBA (database block address). Eg: variable x varchar2; exec :x := dbms_utility.make_data_block_address(1,12); print x alter session set events 'immediate trace name blockdump level 50360894' / What are the different kind of export backups? Full back - Complete database Incremental - Only affected tables from last incremental date/full backup date. Cumulative backup - Only affected table from the last cumulative date/full backup date. How free extents are managed in Ver 6.0 and Ver 7.0 ? Free extents cannot be merged together in Ver 6.0.

Free extents are periodically coalesces with the neighboring free extent in Ver 7.0 What is the use of RECORD option in EXP command? For Incremental exports, the flag indirects whether a record will be stores data dictionary tables recording the export. What is the use of ROWS option in EXP command ? Flag to indicate whether table rows should be exported. If 'N' only DDL statements for the database objects will be created. What is the use of COMPRESS option in EXP command ? Flag to indicate whether export should compress fragmented segments into single extents. How will you swap objects into a different table space for an existing database ? Export the user Perform import using the command imp system/manager file=export.dmp indexfile=newrite.sql. This will create all definitions into newfile.sql. Drop necessary objects. Run the script newfile.sql after altering the tablespaces. Import from the backup for the necessary objects. How does Space allocation table place within a block ? Each block contains entries as follows Fixed block header Variable block header Row Header,row date (multiple rows may exists) PCTEREE (% of free space for row updation in future) What are the factors causing the reparsing of SQL statements in SGA? Due to insufficient Shared SQL pool size. Monitor the ratio of the reloads takes place while executing SQL statements. If the ratio is greater than 1 then increase the SHARED_POOL_SIZE. LOGICAL & PHYSICAL ARCHITECTURE OF DATABASE. What is dictionary cache ? Dictionary cache is information about the databse objects stored in a data dictionary table. What is a Control file ? Database overall physical architecture is maintained in a file called control file. It will be used to maintain internal consistency and guide recovery operations. Multiple copies of control files are advisable. What is Database Buffers ? Database buffers are cache in the SGA used to hold the data blocks that are read from the data segments in the database such as tables, indexes and clusters DB_BLOCK_BUFFERS parameter in INIT.ORA decides the size. How will you create multiple rollback segments in a database ? Create a database which implicitly creates a SYSTEM Rollback Segment in a SYSTEM tablespace. Create a Second Rollback Segment name R0 in the SYSTEM tablespace. Make new rollback segment available (After shutdown, modify init.ora file and Start database) Create other tablespaces (RBS) for rollback segments. Deactivate Rollback Segment R0 and activate the newly created rollback segments.

What is cold backup? What are the elements of it? Cold backup is taking backup of all physical files after normal shutdown of database. We need to take. - All Data files. - All Control files. - All on-line redo log files. - The init.ora file (Optional) What is meant by redo log buffer ? Changes made to entries are written to the on-line redo log files. So that they can be used in roll forward operations during database recoveries. Before writing them into the redo log files, they will first brought to redo log buffers in SGA and LGWR will write into files frequently. LOG_BUFFER parameter will decide the size. How will you estimate the space required by a non-clustered tables? Calculate the total header size Calculate the available dataspace per data block Calculate the combined column lengths of the average row Calculate the total average row size. Calculate the average number rows that can fit in a block Calculate the number of blocks and bytes required for the table. After arriving the calculation, add 10 % additional space to calculate the initial extent size for a working table. How will you monitor the space allocation ? By querying DBA_SEGMENT table/view. What is meant by free extent ? A free extent is a collection of continuous free blocks in tablespace. When a segment is dropped its extents are reallocated and are marked as free. What is the use of IGNORE option in IMP command ? A flag to indicate whether the import should ignore errors encounter when issuing CREATE commands. What is the use of ANALYSE ( Ver 7) option in EXP command ? A flag to indicate whether statistical information about the exported objects should be written to export dump file. What is the use of ROWS option in IMP command ? A flag to indicate whether rows should be imported. If this is set to 'N' then only DDL for database objects will be executed. What is the use of INDEXES option in EXP command ? A flag to indicate whether indexes on tables will be exported. What is the use of INDEXES option in IMP command ? A flag to indicate whether import should import index on tables or not. What is the use of GRANT option in EXP command? A flag to indicate whether grants on databse objects will be exported or not. Value is 'Y' or 'N'. What is the use of GRANT option in IMP command ? A flag to indicate whether grants on database objects will be imported.

What is the use of FULL option in EXP command ? A flag to indicate whether full databse export should be performed. What is the use of SHOW option in IMP command ? A flag to indicate whether file content should be displayed or not. What is the use of CONSTRAINTS option in EXP command ? A flag to indicate whether constraints on table need to be exported. What is the use of CONSISTENT (Ver 7) option in EXP command ? A flag to indicate whether a read consistent version of all the exported objects should be maintained. What are the different methods of backing up oracle database ? - Logical Backups - Cold Backups - Hot Backups (Archive log) What is the difference between ON-VALIDATE-FIELD trigger and a POST-CHANGE trigger ? When you changes the Existing value to null, the On-validate field trigger will fire post change trigger will not fire. At the time of execute-query post-change trigger will fire, on-validate field trigger will not fire. When is PRE-QUERY trigger executed ? When Execute-query or count-query Package procedures are invoked.

How do you trap the error in forms 3.0 ? using On-Message or On-Error triggers. How many pages you can in a single form ? Unlimited While specifying master/detail relationship between two blocks specifying the join condition is a must ? True or False. ? True EXIT_FORM is a restricted package procedure ? a. True b. False True What is the usage of an ON-INSERT,ON-DELETE and ON-UPDATE TRIGGERS ? These triggers are executes when inserting, deleting and updating operations are performed and can be used to change the default function of insert, delete or update respectively. For Eg, instead of inserting a row in a table an existing row can be updated in the same table. What are the types of Pop-up window ? the pop-up field editor pop-up list of values pop-up pages.

Alert : What is an SQL *FORMS ? SQL *forms is 4GL tool for developing and executing; Oracle based interactive application. How do you control the constraints in forms ? Select the use constraint property is ON Block definition screen. BLOCK What is the difference between restricted and unrestricted package procedure ? Restricted package procedure that affects the basic functions of SQL * Forms. It cannot used in all triggers except key triggers. Unrestricted package procedure that does not interfere with the basic functions of SQL * Forms it can be used in any triggers. A query fetched 10 records How many times does a PRE -QUERY Trigger and POST-QUERY Trigger will get executed ? PRE-QUERY fires once. POST-QUERY fires 10 times. Give the sequence in which triggers fired during insert operations, when the following 3 triggers are defined at the same block level ? a. ON-INSERT b. POST-INSERT c. PRE-INSERT State the order in which these triggers are executed ? POST-FIELD,ON-VALIDATE-FIELD,POST-CHANGE and KEY-NEXTFLD. KEY-NEXTFLD,POST-CHANGE, ON-VALIDATEFIELD, POST-FIELD. g. What the PAUSE package procedure does ? Pause suspends processing until the operator presses a function key What do you mean by a page ? Pages are collection of display information, such as constant text and graphics What are the type of User Exits ? ORACLE Precompliers user exits OCI (ORACLE Call Interface) Non-ORACEL user exits. Page : What is the difference between an ON-VALIDATE-FIELD trigger and a trigger ? On-validate-field trigger fires, when the field Validation status New or changed. Post -field-trigger whenever the control leaving form the field, it will fire. Can we use a restricted package procedure in ON -VALIDATE-FIELD Trigger ? No Is a Key startup trigger fires as result of a operator pressing a key explicitly ? No Can we use GO-BLOCK package in a pre-field trigger ?

No Can we create two blocks with the same name in form 3.0 ? No What does an on-clear-block Trigger fire? It fires just before SQL * forms the current block. Name the two files that are created when you generate the form give the filex extension ? INP (Source File) FRM (Executable File) What package procedure used for invoke sql *plus from sql *forms ? Host (E.g. Host (sqlplus)) What is the significance of PAGE 0 in forms 3.0 ? Hide the fields for internal calculation. What are the different types of key triggers ? Function Key Key-function Key-others Key-startup What is the difference between a Function Key Trigger and Key Function Trigger ? Function key triggers are associated with individual SQL*FORMS function keys You can attach Key function triggers to 10 keys or key sequences that normally do not perform any SQL * FORMS operations. These keys referred as key F0 through key F9. Committed block sometimes refer to a BASE TABLE ? False Error_Code is a package proecdure ? a. True b. false False When is cost based optimization triggered? (for DBA) It's important to have statistics on all tables for the CBO (Cost Based Optimizer) to work correctly. If one table involved in a statement does not have statistics, Oracle has to revert to rule -based optimization for that statement. So you really want for all tables to have statistics right away; it won't help much to just have the larger tables analyzed. Generally, the CBO can change the execution plan when you: 1. Change statistics of objects by doing an ANALYZE; 2. Change some initialization parameters (for example: hash_join_enabled, sort_area_size, db_file_multiblock_read_count). How can one optimize %XYZ% queries? (for DBA) It is possible to improve %XYZ% queries by forcing the optimizer to scan all the entries from the index instead of the table. This can be done by specifying hints. If the index is physically smaller than the table (which is usually the

case) it will take less time to scan the entire index than to scan the entire table. What Enter package procedure does ? Enter Validate-data in the current validation unit. Where can one find I/O statistics per table? (for DBA) The UTLESTAT report shows I/O per tablespace but one cannot see what tables in the tablespace has the most I/O. The $ORACLE_HOME/rdbms/admin/catio.sql script creates a sample_io procedure and table to gather the required information. After executing the procedure, one can do a simple SELECT * FROM io_per_object; to extract the required information. For more details, look at the header comments in the $ORACLE_HOME/rdbms/admin/catio.sql script. My query was fine last week and now it is slow. Why? (for DBA) The likely cause of this is because the execution plan has changed. Generate a current explain plan of the offending query and compare it to a previous one that was taken when the query was performing well. Usually the previous plan is not available. Some factors that can cause a plan to change are: . Which tables are currently analyzed? Were they previously analyzed? (ie. Was the query using RBO and now CBO?) . Has OPTIMIZER_MODE been changed in INIT.ORA? . Has the DEGREE of parallelism been defined/changed on any table? . Have the tables been re-analyzed? Were the tables analyzed using estimate or compute? If estimate, what percentage was used? . Have the statistics changed? . Has the INIT.ORA parameter DB_FILE_MULTIBLOCK_READ_COUNT been changed? . Has the INIT.ORA parameter SORT_AREA_SIZE been changed? . Have any other INIT.ORA parameters been changed? . What do you think the plan should be? Run the query with hints to see if this produces the required performance. Why is Oracle not using the damn index? (for DBA) This problem normally only arises when the query plan is being generated by the Cost Based Optimizer. The usual cause is because the CBO calculates that executing a Full Table Scan would be faster than accessing the table via the index. Fundamental things that can be checked are: . USER_TAB_COLUMNS.NUM_DISTINCT - This column defines the number of distinct values the column holds. . USER_TABLES.NUM_ROWS - If NUM_DISTINCT = NUM_ROWS then using an index would be preferable to doing a FULL TABLE SCAN. As the NUM_DISTINCT decreases, the cost of using an index increase thereby is making the index less desirable. . USER_INDEXES.CLUSTERING_FACTOR - This defines how ordered the rows are in the index. If CLUSTERING_FACTOR approaches the number of blocks in the table, the rows are ordered. If it approaches the number of rows in the table, the rows are randomly ordered. In such a case, it is unlikely that index entries in the same leaf block will point to rows in the same data blocks. . Decrease the INIT.ORA parameter DB_FILE_MULTIBLOCK_READ_COUNT - A higher value will make the cost of a FULL TABLE SCAN cheaper. . Remember that you MUST supply the leading column of an index, for the index to be used (unless you use a FAST FULL SCAN or SKIP SCANNING). . There are many other factors that affect the cost, but sometimes the above can help to show why an index is not being used by the CBO. If from checking the above you still feel that the query should be using an index, try specifying an index hint. Obtain an explain plan of the query either using TKPROF with TIMED_STATISTICS, so that

one can see the CPU utilization, or with AUTOTRACE to see the statistics. Compare this to the explain plan when not using an index. When should one rebuild an index? (for DBA) You can run the 'ANALYZE INDEX VALIDATE STRUCTURE' command on the affected indexes - each invocation of this command creates a single row in the INDEX_STATS view. This row is overwritten by the next ANALYZE INDEX command, so copy the contents of the view into a local table after each ANALYZE. The 'badness' of the index can then be judged by the ratio of 'DEL_LF_ROWS' to 'LF_ROWS'. What are the unrestricted procedures used to change the popup screen position during run time ? Anchor-view Resize -View Move-View. What is an Alert ? An alert is window that appears in the middle of the screen overlaying a portion of the current display. Deleting a page removes information about all the fields in that page ? a. True. b. False? a. True. Two popup pages can appear on the screen at a time ?Two popup pages can appear on the screen at a time ? a. True. b. False? a. True. Classify the restricted and unrestricted procedure from the following. a. Call b. User-Exit c. Call-Query d. Up e. Execute-Query f. Message g. Exit-From h. Post i. Break? a. Call - unrestricted b. User Exit - Unrestricted c. Call_query - Unrestricted d. Up - Restricted e. Execute Query - Restricted f. Message - Restricted g. Exit_form - Restricted h. Post - Restricted i. Break - Unrestricted. What is an User Exits ? A user exit is a subroutine which are written in programming languages using pro*C pro *Cobol , etc., that link into the SQL * forms executable.

What is a Trigger ? A piece of logic that is executed at or triggered by a SQL *forms event. What is a Package Procedure ? A Package procedure is built in PL/SQL procedure. What is the maximum size of a form ? 255 character width and 255 characters Length. What is the difference between system.current_field and system.cursor_field ? 1. System.current_field gives name of the field. 2. System.cursor_field gives name of the field with block name. List the system variables related in Block and Field? 1. System.block_status 2. System.current_block 3. System.current_field 4. System.current_value 5. System.cursor_block 6. System.cursor_field 7. System.field_status. What are the different types of Package Procedure ? 1. Restricted package procedure. 2. Unrestricted package procedure. What are the types of TRIGGERS ? 1. Navigational Triggers. 2. Transaction Triggers. Identify package function from the following ? 1. Error-Code 2. Break 3. Call 4. Error-text 5. Form-failure 6. Form-fatal 7. Execute-query 8. Anchor View 9. Message_code? 1. Error_Code 2. Error_Text 3. Form_Failure 4. Form_Fatal 5. Message_Code Can you attach an lov to a field at run-time? if yes, give the build-in name.?

Yes. Set_item_proprety Is it possible to attach same library to more than one form? Yes Can you attach an lov to a field at design time? Yes List the windows event triggers available in Forms 4.0? When-window-activated, when-window-closed, when-window-deactivated, when-window-resized What are the triggers associated with the image item? When-Image-activated(Fires when the operator double clicks on an image Items) When-image-pressed(fires when the operator selects or deselects the image item) What is a visual attribute? Visual Attributes are the font, color and pattern characteristics of objects that operators see and intract with in our application. How many maximum number of radio buttons can you assign to a radio group? Unlimited no of radio buttons can be assigned to a radio group How do you pass the parameters from one form to another form? To pass one or more parameters to a called form, the calling form must perform the following steps in a trigger or user named routine execute the create_parameter_list built-in function to programmatically. Create a parameter list to execute the add parameter built-in procedure to add one or more parameters list. Execute the call_form, New_form or run_product built_in procedure and include the name or id of the parameter list to be passed to the called form. What is a Layout Editor? The Layout Editor is a graphical design facility for creating and arranging items and boilerplate text and graphics objects in your application's interface. List the Types of Items? Text item. Chart item. Check box. Display item. Image item. List item. Radio Group. User Area item. List system variables available in forms 4.0, and not available in forms 3.0? System.cordination_operation System Date_threshold System.effective_Date

System.event_window System.suppress_working What are the display styles of an alert? Stop, Caution, note What built-in is used for showing the alert during run-time? Show_alert. What built-in is used for changing the properties of the window dynamically? Set_window_property Canvas-View What are the different types of windows? Root window, secondary window. What is a predefined exception available in forms 4.0? Raise form_trigger_failure What is a radio Group? Radio groups display a fixed no of options that are mutually Exclusive. User can select one out of n number of options. What are the different type of a record group? Query record group Static record group Non query record group What are the menu items that oracle forms 4.0 supports? Plain, Check,Radio, Separator, Magic Give the equivalent term in forms 4.0 for the following. Page, Page 0? Page - Canvas-View Page 0 - Canvas-view null. What triggers are associated with the radio group? Only when-radio-changed trigger associated with radio group Visual Attributes. What are the triggers associated with a check box? Only When-checkbox-activated Trigger associated with a Check box. Can you attach an alert to a field? No Can a root window be made modal? No What is a list item?

It is a list of text elements. List some built-in routines used to manipulate images in image_item? Image_add Image_and Image_subtract Image_xor Image_zoom Can you change the alert messages at run-time? If yes, give the name of the built-in to change the alert messages at run-time. Yes. Set_alert_property. What is the built-in used to get and set lov properties during run-time? Get_lov_property Set_lov_property Record Group What is the built-in routine used to count the no of rows in a group? Get_group _row_count System Variables Give the Types of modules in a form? Form Menu Library Write the Abbreviation for the following File Extension 1. FMB 2. MMB 3. PLL? FMB ----- Form Module Binary. MMB ----- Menu Module Binary. PLL ------ PL/SQL Library Module Binary. List the built-in routine for controlling window during run-time? Find_window, get_window_property, hide_window, move_window, resize_window, set_window_property, show_View List the built-in routine for controlling window during run-time? Find_canvas Get-Canvas_property Get_view_property Hide_View Replace_content_view Scroll_view Set_canvas_property Set_view_property

Show_view Alert What is the built-in function used for finding the alert? Find_alert Editors List the editors availables in forms 4.0? Default editor User_defined editors system editors. What buil-in routines are used to display editor dynamicaly? Edit_text item show_editor

DB Interview Questions Question: What is SQL? Question: What is SELECT statement? Question: How can you compare a part of the name rather than the entire name? Question: What is the INSERT statement? Question: How do you delete a record from a database? Question: How could I get distinct entries from a table? Question: How to get the results of a Query sorted in any order? Question: How can I find the total number of records in a table? Question: What is GROUP BY? Question: What is the difference among "dropping a table", "truncating a table" and "deleting all records" from a table? Question: What are the Large object types suported by Oracle? Question: Difference between a "where" clause and a "having" clause ? Question: What's the difference between a primary key and a unique key? Question: What are cursors? Explain different types of cursors. What are the disadvantages of cursors? How can you avoid cursors?

Question: What are triggers? How to invoke a trigger on demand? Question: What is a join and explain different types of joins. Question: What is a self join?

Q: What is SQL? A: SQL stands for 'Structured Query Language'.

Q: What is SELECT statement? A: The SELECT statement lets you select a set of values from a table in a database. The values selected from the database table would depend on the various conditions that are specified in the SQL query.

Q: How can you compare a part of the name rather than the entire name? A: SELECT * FROM people WHERE empname LIKE '%ab%' Would return a recordset with records consisting empname the sequence 'ab' in empname .

Q: What is the INSERT statement? A: The INSERT statement lets you insert information into a database. Q: How do you delete a record from a database? A: Use the DELETE statement to remove records or any particular column values from a database.

Q: How could I get distinct entries from a table? A: The SELECT statement in conjunction with DISTINCT lets you select a set of distinct values from a table in a database. The values selected from the database table would of course depend on the various conditions that are specified in the SQL query. Example SELECT DISTINCT empname FROM emptable

Q: How to get the results of a Query sorted in any order? A: You can sort the results and return the sorted results to your program by using ORDER BY keyword thus saving you the pain of carrying out the sorting yourself. The ORDER BY keyword is used for sorting. SELECT empname, age, city FROM emptable ORDER BY empname

Q: How can I find the total number of records in a table?

A: You could use the COUNT keyword , example SELECT COUNT(*) FROM emp WHERE age>40

Q: What is GROUP BY? A: The GROUP BY keywords have been added to SQL because aggregate functions (like SUM) return the aggregate of all column values every time they are called. Without the GROUP BY functionality, finding the sum for each individual group of column values was not possible.

Q: What is the difference among "dropping a table", "truncating a table" and "deleting all records" from a table. A: Dropping : (Table structure + Data are deleted), Invalidates the dependent objects ,Drops the indexes Truncating: (Data alone deleted), Performs an automatic commit, Faster than delete Delete : (Data alone deleted), Doesn?t perform automatic commit

Q: What are the Large object types suported by Oracle? A: Blob and Clob.

Q: Difference between a "where" clause and a "having" clause. A: Having clause is used only with group functions whereas Where is not used with.

Q: What's the difference between a primary key and a unique key? A: Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn't allow NULLs, but unique key allows one NULL only.

Q: What are cursors? Explain different types of cursors. What are the disadvantages of cursors? How can you avoid cursors? A: Cursors allow row-by-row prcessing of the resultsets. Types of cursors: Static, Dynamic, Forward-only, Keyset-driven. See books online for more information. Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a network roundtrip, where as a normal SELECT query makes only one rowundtrip, however large the resultset is. Cursors are also costly because they require more resources and temporary storage (results in more IO operations). Furthere, there are restrictions on the SELECT statements that can be used with some types of cursors. Most of the times, set based operations can be used instead of cursors. Q: What are triggers? How to invoke a trigger on demand? A: Triggers are special kind of stored procedures that get executed automatically when an INSERT, UPDATE or

DELETE operation takes place on a table. Triggers can't be invoked on demand. They get triggered only when an associated action (INSERT, UPDATE, DELETE) happens on the table on which they are defined. Triggers are generally used to implement business rules, auditing. Triggers can also be used to extend the referential integrity checks, but wherever possible, use constraints for this purpose, instead of triggers, as constraints are much faster. Q: What is a join and explain different types of joins. A: Joins are used in queries to explain how different tables are related. Joins also let you select data from a table depending upon data from another table. Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further classified as LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS. Q: What is a self join? A: Self join is just like any other join, except that two instances of the same table will be joined in the query.

How can I see my PL/SQL output ????


In SQL*Plus or in your script add this line before your excute SQL> set serveroutput on SQL> execute xxxxxxxxxxx.yyyyyyyyyyyyy; and you will see this: PL/SQL procedure successfully completed.

How can I retrieve a random number ?

SQL> select dbms_random.random from dual; RANDOM ---------495129087 Using SQL*Plus how can I produce a flat file without headings, feedback, etc ? Try these set commands just before your spool command. set newpage 0 set space 0 set linesize 80 set pagesize 0 set echo off set feedback off set heading off How to move a file from one folder to other folder using SQLPLUS?

SQL> host cp /home/oracle/text.log /home/oracle/test.log sql query to retrieve the first day of the month...

select to_char(trunc(sysdate,'MM'),'DAY') from dual Query to get the number of days between two dates is easy to get

select months_between(to_date('01/06/2004','MM/DD/YYYY'), to_date('01/06/2003','MM/DD/YYYY'))/12 "Years", months_between(to_date('01/06/2004','MM/DD/YYYY'), to_date('01/06/2003','MM/DD/YYYY')) "Total Months", to_date('01/06/2004','MM/DD/YYYY') to_date('01/06/2003','MM/DD/YYYY') "Total Days" from dual Query to extract the given string 'a;b;c;d;e;f' as (a b c d e f)

select col1,col2,col3,col4, trim(substr(col,1,instr(col,';')-1)) col5, ltrim(substr(col,instr(col,';')+1)) col6 from( select col1,col2,col3, trim(substr(col,1,instr(col,';')-1)) col4, ltrim(substr(col,instr(col,';')+1)) col from( select col1,col2, trim(substr(col,1,instr(col,';')-1)) col3, ltrim(substr(col,instr(col,';')+1)) col from( select col1, trim(substr(col,1,instr(col,';')-1)) col2, ltrim(substr(col,instr(col,';')+1)) col from( select trim(substr(col,1,instr(col,';')-1)) col1, ltrim(substr(col,instr(col,';')+1)) col from( select 'a;b;c;d;e;f' col from dual ))))) . Following is the query Table 1 Col1 2 5 7

9 4 6 Query output to be as follows (row1+row2) 2+5=7 (row2+row3) 5+7 =12 (row3+row4) 7+9=16 etc etc select col1,col1+nextval from (select col1, lead(col1,1) over(order by rn) as nextval from (select rownum rn,col1 from table1) ) OR Another Solution SELECT * FROM (SELECT col1 , LAG(col1) OVER (ORDER BY row_num) AS prev , LAG(col1) OVER (ORDER BY row_num)+ col1 scol1 FROM (SELECT ROWNUM row_num, col1 FROM table1) ) WHERE scol1 IS NOT NULL Following is the Query?O/P Wanted ! Table A ------SNo Sname 1a 2b 3c Table B -------SNo Course 1x 1y 1k 1z 2x 2z 2d 3y 3z 3e I need the output in the following format where course is x or y or z.

1xyz 2xz 3yz select a.sno, x.course x, y.course y, z.course z,j.course j from a, (select sno, course from b where course = 'x') x, (select sno, course from b where course = 'y') y, (select sno, course from b where course = 'z') z, (select sno, course from b where course = 'j') j where a.sno = x.sno(+) and a.sno = y.sno(+) and a.sno = z.sno(+) and a.sno = j.sno(+) The Follwing is the Query id date --------------1 NULL 1 NULL 1 NULL 2 NULL 2 21.03.2004 3 22.04.2003 3 10.04.2003 Want the id when the date is never filled Output shud return as ID 1 select distinct t1.id from t1 where not exists (select null from t2 where t2.id = t1.id and t2.mydate is not null) Following is the Query IF I HAVE TWO COLUMNS LIKE THAT ID COLUMN A 1 A 10000 2 Z 20000 3 I 30000 4 Z 40000 5 P 50000 6 D 60000 7 A 70000 8 P 80000 9 I 90000 COLUMN B

Find the Query which will SUM THE COLUMN B, GROUP BY COLUMN A WITHOUT DISTRUBING THE SEQUENCE Output shud be as A 80000 Z 60000 I 12000 P 13000

D 6000 select col1,sum(col2) from t3 group by col1 How to find only the duplicate records select name,count(*) from X1 group by name having count(*)>1 Is there a limit on the size of a PL/SQL block? 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' What is the use of Data Dictionary ? Used by Oracle to store information about various physical and logical Oracle structures e.g. Tables, Tablespaces, datafiles, etc If you insert a row in a table, then create another table and then say Rollback. In this case will the row be inserted ? 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. What are the parts of a database trigger ? The parts of a trigger are: A triggering event or statement A trigger restriction A trigger action What are the various types of database triggers ? There are 12 types of triggers, they are combination of : Insert, Delete and Update Triggers. Before and After Triggers. Row and Statement Triggers. (3*2*2=12) What is the advantage of a stored procedure over a database trigger ? We have control over the firing of a stored procedure but we have no control over the firing of a trigger. What is the maximum no. of statements that can be specified in a trigger statement ? One. Can views be specified in a trigger statement ? No What are the values of :new and :old in Insert/Delete/Update Triggers ?

INSERT : new = new value, old = NULL DELETE : new = NULL, old = old value UPDATE : new = new value, old = old value What are cascading triggers? What is the maximum no of cascading triggers at a time? When a statement in a trigger body causes another trigger to be fired, the triggers are said to be cascading. Max = 32. What are mutating triggers ? A trigger giving a SELECT on the table on which the trigger is written. What are constraining triggers ? A trigger giving an Insert/Update on a table having referential integrity constraint on the triggering table. What are constraining triggers ? A trigger giving an Insert/Update on a table having referential integrity constraint on the triggering table. Describe Oracle database's physical and logical structure ? Physical : Data files, Redo Log files, Control file. Logical : Tables, Views, Tablespaces, etc. Procedures with FUNCTIONS declare n number := &empno; b number; function f1 (a number) return number is s number; begin select sal into s from emp where empno = n; return (s*0.10); end;

BEGIN -- Main procedure b := f1(n); dbms_output.put_line(b); End; PROCEDURES AS STORED PROGRAM UNITS create or replace procedure p1 (emp number) is begin update emp1 set sal = sal*1.10 where empno = emp; end; Calling a stored procedure within the main procedure

declare e = emp.empno%type :=&empno ; begin p1(e); end; Can 2 functions have same name & input parameters but differ only by return data type No. What are the constructs of a procedure, function or a package ? The constructs of a procedure, function or a package are : variables and constants cursors exceptions Why Create or Replace, and not Drop and recreate procedures ? So that Grants are not dropped. Procedure to check for PALINDROME and to print the reverse of the string ## procedure created using concatenate function ## declare word varchar2(15) := '&word'; r_word varchar2(15); c char(1); n integer(2); begin n := length(word); for i in reverse 1..n loop c :=substr(word,i,1); r_word := concat(r_word,c); end loop; /* to display the reverse of the string */ dbms_output.put_line('The reverse of the string is '||r_word); if r_word != word then dbms_output.put_line('Not a PALINDROME word'); else dbms_output.put_line('PALINDROME word'); end if ; end; Procedure for scope of variables

declare a number:=5; begin declare a number:=10; -- the scope of this variable is limited -- only to this block b number:=6; begin dbms_output.put_line(a); dbms_output.put_line(b); dbms_output.put_line(a+b); end; dbms_output.put_line(a); end; Procedure with GOTO statement

declare a number:=&num; begin if a >10 then goto aa; else dbms_output.put_line(a); end if;

<<aa>> dbms_output.put_line(a+a); end; Procedure with TOO_MANY_ROWS error handling declare a number; b number; begin select sal into a from emp where empno = 7900; dbms_output.put_line ('Salary is '|| a); select ename into b from emp where empno = 7900; dbms_output.put_line (b); exception when too_many_rows then dbms_output.put_line ('Too Many Rows... '); when no_data_found then dbms_output.put_line ('Invalid EMPNO... '); when value_error then dbms_output.put_line ('Data Mismatch... '); end; Procedure with USER-DEFINED EXCEPTIONS declare

ude1 exception; -- to indicate that the exceptional errors a number; begin select sal into a from emp where empno = 7900; if a <4000 then raise ude1; else dbms_output.put_line('The salary is '||a); end if; exception when ude1 then dbms_output.put_line('Poor salary ...'); end; Procedure with RECORDS

## This is used to process several records at the same time #### declare Type emprec is record (name emp.ename%type, salary emp.sal%type, dob emp.hiredate%type); a emprec; begin select ename,sal,hiredate into a from emp where job = 'PRESIDENT'; dbms_output.put_line ('The features are '|| a.name || a.salary || a.dob); end; Procedure with EXCEPTIONS

declare emp emp1.empno%type; name emp1.ename%type; sal1 emp1.sal%type; num number; cursor c1 is select empno,ename,sal from emp1; begin -- select sal into num from emp1 where mgr=7839; open c1; loop fetch c1 into emp,name,sal1; exit when c1%notfound; end loop; exception when too_many_rows then declare

cursor c2 is select max(sal) from emp where mgr=7839; begin open c2; update emp1 set comm = 500 where empno = 7839; close c2; end; close c1; end; Procedure to select 1st 'n' higest persons & salaries using PL/SQL declare cursor c1 is select ename,sal from emp order by sal desc; a emp.sal%type; b emp.ename%type; n number :=&num; begin open c1; loop fetch c1 into b,a; exit when c1%rowcount =6; dbms_output.put_line(b||' '||a); end loop; end; Procedure to find the nth maximum salary use PL/SQL ## Procedure created using parameterized cursors ## ## This procedure eliminates the highest salaries step by step in the outer loop ## declare cursor c1(a number) is select sal from emp where sal <a ; a number := 1000000; -- random high salary for comparison b number :=0; -- initializing variable also n number(2) :=&num; begin for i in 1..n loop for j in c1(a) loop if b<j.sal then b:= j.sal; end if; end loop; a := b; b := 0; end loop; dbms_output.put_line('The '||n||'th maximum salary is '||a);

close c1; end; Program to generate Prime Numbers declare i number := &num; flag number(1) :=0; begin for l in 2..i loop for m in 2..l-1 loop if mod(l,m) = 0 then flag := 1; exit; end if; end loop; if flag = 0 then dbms_output.put_line('* '||l); end if; flag := 0; end loop; end; Stripping part Numbers of unwanted characters declare ptno char(22); begin dbms_output.put_line ('Enter the unstripped part Number '); ptno := '&ptno'; select replace(ptno,' ') into ptno from dual; select replace(ptno,'.') into ptno from dual; select replace(ptno,'*') into ptno from dual; select replace(ptno,'-') into ptno from dual; dbms_output.put_line ('The stripped part Number is '||ptno); end; Program to print reverse of values

declare a number(2); b number(2); begin dbms_output.put_line('PROGRAM TO PRINT REVERSE VALUES'); a:= &a; b:= &b; a:= a+b; b:= a - b; a:= a-b;

dbms_output.put_line('New value of a is '||a); dbms_output.put_line('New value of b is '||b); end; SIMPLE PROGRAM USING PARAMETERIZED CURSOR

DECLARE name emp.ename%type; dept emp.deptno%type; gsal emp.sal%type; cursor c1(salary number) is select ename,deptno,sal from emp where sal >salary; BEGIN open c1(3000); dbms_output.put_line('NAME DEPARTMENT salary'); loop fetch c1 into name,dept,gsal; exit when c1%notfound; dbms_output.put_line(name||' '||dept||' '||gsal); end loop; close c1; END; SIMPLE PROGRAM IMPLEMENT EXPLICIT CURSORS

DECLARE name emp.ename%type; dept emp.deptno%type; cursor c1 is select ename,deptno from emp where sal >2000; BEGIN open c1; dbms_output.put_line('NAME DEPARTMENT'); loop fetch c1 into name, dept; exit when c1%notfound; dbms_output.put_line(name||' '||dept); end loop; close c1; END; PROGRAM TO GENERATE MULTIPLICATION TABLE FOR A NUMBER 'n' DECLARE n number := &n; prod number;

BEGIN for i in 1..10 loop prod := n * i; dbms_output.put_line(n||' * '||lpad(i,2,' ') ||' = '||lpad(prod,3,' ')); end loop; END; PROGRAM TO GENERATE FIBONACCI SERIES UPTO 'n' NUMBERS DECLARE n number := &n; t1 number := 0; t2 number := 1; t3 number; BEGIN dbms_output.put_line(t1); dbms_output.put_line(t2); for i in 3..n loop t3 := t1 + t2; dbms_output.put_line(t3); t1 := t2; t2 := t3; end loop; END; PROGRAM TO CHECK A STRING FOR PALINDROME

DECLARE len number; palstr varchar2(20) := '&palstr'; chkstr varchar2(20); BEGIN len := length(palstr); for i in REVERSE 1..len loop chkstr := chkstr||substr(palstr,i,1); end loop; if chkstr = palstr then dbms_output.put_line(palstr||' is a PALINDROME'); else dbms_output.put_line(palstr||' is not a PALINDROME'); end if; END; PROGRAM TO REVERSE A GIVEN STRING DECLARE len number; str varchar2(20) := '&str'; rev_str varchar2(20); conchar char(1);

BEGIN len := length(str); for i in REVERSE 1..len loop conchar := substr(str,i,1); rev_str := rev_str||conchar; end loop; dbms_output.put_line('REVERSED STRING IS : '||rev_str); END; PROGRAM TO FIND ODD & EVEN NUMBERS BEGIN for i in 1..10 loop if mod(i,2) = 0 then dbms_output.put_line(i||' is an even number'); else dbms_output.put_line(i||' is an odd number'); end if; end loop; END; Query to find the #week from the date given select to_char(sysdate, 'ww') from dual; Query as follows /* query asked */ Say in Table ?T? I have two colums ?A?, ? B? I want to get the sum of A based on values of B. I should get the sum in two buckets For B=0 And B not equal zero. Example AB ___ ___ 10 21 30 43 52 60 So I should get the result set as SUM (A) B ______ __________ 10 For B=ZERO 11 For B=NONZERO

/* Solution */

Select decode(b,0,'B=ZERO','B=NONZERO') B, sum(a) from t group by decode(b,0,'B=ZERO','B=NONZERO') /* Solution */ Select decode(X, 0, 'Zero', 'Non-Zero'), sum(Y) from ( select decode(B, 0, 0, 1) X, Y from T group by decode(B, 0, 0, 1) ) Query as below /* query asked*/ If an employee taken continues leave from 25-Feb-2006 to 03-Apr-2006, we have to display the monthly leave breakup like Feb ? 4 Days, Mar ? 31 Days and Apr ? 3 Days. How to write a procedure, Please advice us. Record it will be store in Start Date : 25-Feb-2006 End Date : 03-Apr-2006 Notification Date : 25-Feb-2006 No of Days : 38 /* Solution*/ select (dt2-dt1+1) days,ddd.* from ( select greatest(start_date,startdt) dt1,least(end_date,enddt) dt2, leave.*,months.* from (select to_date('25-Feb-2006','dd-mon-yyyy') Notification_date, to_date('25-Feb-2006','dd-mon-yyyy') start_date, to_date('03-Apr-2006','dd-mon-yyyy') end_date from dual ) leave, (select trunc(asofdate,'mm') startdt,last_day(asofdate) enddt from ( select trunc(add_months(sysdate,l-6),'mm') asofdate from (select level l from dual connect by level<12) )) months where months.startdt between leave.start_date and leave.end_date or months.enddt between leave.start_date and leave.end_date

) ddd

Query as follows I have a query as below: select quantity from material_table. quantity --------20 40 10 I want the query to return only first two records (i.e. to stop the query when the sum of quantity is 60 in this case). /* Solution*/ select quantity from ( select quantity, sum(quantity) over ( order by transaction_date range unbounded preceding ) as running_sum from material_table ) where running_sum<=60 Following is the query SQL> DESC PATH Name Null? Type ------------------------------- -------- ---COL1 CHAR(1) COL2 CHAR(1) SQL> select * from path; Col1 Col2 ------ -----AB BC BD CM DG MH RY 7 rows selected. the result to be as follows B,C,C,M,M,H PL/SQL version, which can be easily converted into a procedure: DECLARE result VARCHAR2(100); BEGIN FOR i IN (SELECT * FROM path START WITH col2 = 'H'

CONNECT BY PRIOR col1 = col2) LOOP result := i.col1 || ', ' || i.col2 || ', ' || result; IF i.col1 != 'B' THEN null; END IF; END LOOP; Dbms_Output.Put_Line(result); END; OUTPUT: A, B, B, C, C, M, M, H, SYS_CONNECT_BY_PATH implementation and examples in Oracle 9i 9i has a new function SYS_CONNECT_BY_PATH, which is probably best explained with the following example: SQL > select * from scott.emp 2/

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO ----- --------------- ---------- ---------- ---------- --------- ------- -----7369 SMITH CLERK 7902 17/12/1980 800.00 20 7499 ALLEN SALESMAN 7698 20/02/1981 1600.00 300.00 30 7521 WARD SALESMAN 7698 22/02/1981 1250.00 500.00 30 7566 JONES MANAGER 7839 02/04/1981 2975.00 20 7654 MARTIN SALESMAN 7698 28/09/1981 1250.00 1400.00 30 7698 BLAKE MANAGER 7839 01/05/1981 2850.00 30 7782 CLARK MANAGER 7839 09/06/1981 2450.00 10 7788 SCOTT ANALYST 7566 19/04/1987 3000.00 20 7839 KING PRESIDENT 17/11/1981 5000.00 10 7844 TURNER SALESMAN 7698 08/09/1981 1500.00 .00 30 7876 ADAMS CLERK 7788 23/05/1987 1100.00 20 7900 JAMES CLERK 7698 03/12/1981 950.00 30 7902 FORD ANALYST 7566 03/12/1981 3000.00 20 7934 MILLER CLERK 7782 23/01/1982 1300.00 10 14 rows selected. SQL> SELECT LPAD(' ', 2*LEVEL1)||SYS_CONNECT_BY_PATH(ename, '/') "Path" 2 FROM scott.emp 3 START WITH ename = 'KING' 4 CONNECT BY PRIOR empno = mgr; Path /KING /KING/JONES

/KING/JONES/SCOTT /KING/JONES/SCOTT/ADAMS /KING/JONES/FORD /KING/JONES/FORD/SMITH /KING/BLAKE /KING/BLAKE/ALLEN /KING/BLAKE/WARD /KING/BLAKE/MARTIN /KING/BLAKE/TURNER /KING/BLAKE/JAMES /KING/CLARK /KING/CLARK/MILLER 14 rows selected.

You might also like