Top Banner
Oracle_Questions Some Oracle Related Questions ------------------------ 1.What are the various types of Exceptions ? User defined and Predefined Exceptions. 2.Can we define exceptions twice in same block ? No. 3.What is the difference between a procedure and a function ? Functions return a single variable by value whereas procedures do not return any variable by value. Rather they return multiple variables by passing variables by reference through their OUT parameter. 4.Can you have two functions with the same name in a PL/SQL block ? Yes. 5.Can you have two stored functions with the same name ? Yes. 6.Can you call a stored function in the constraint of a table ? No. 7.What are the various types of parameter modes in a procedure ? IN, OUT AND INOUT. 8.What is Over Loading and what are its restrictions ? OverLoading means an object performing different functions depending upon the no. of parameters or the data type of the parameters passed to it. 9.Can functions be overloaded ? Yes. 10.Can 2 functions have same name & input parameters but differ only by return datatype No. 11.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 12.Why Create or Replace and not Drop and recreate procedures ? So that Grants are not dropped. 13.Can you pass parameters in packages ? How ? Yes. You can pass parameters to procedures or functions in a package. 14.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 15.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) The use of Statement Level Trigger is auditing pops into my head immediately. more detailed security enforcement (prevent the update from happening between 9am and 5pm for example). notification (after trigger - generate an alert to let someone know the data changed). mutating table work arounds (you can read and write the table the trigger fired on in statement triggers). 16.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. 17.What is the maximum no. of statements that can be specified in a trigger statement ? One. 18.Can views be specified in a trigger statement ? No 19.What are the values of :new and :old in Insert/Delete/Update Triggers ? INSERT : new = new value, old = NULL Page 1
114

Oracle Questions

Nov 28, 2014

Download

Documents

rishi5354
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Oracle Questions

Oracle_QuestionsSome Oracle Related Questions------------------------1.What are the various types of Exceptions ?User defined and Predefined Exceptions.2.Can we define exceptions twice in same block ?No.3.What is the difference between a procedure and a function ?Functions return a single variable by value whereas procedures do not return any variable by value. Rather they return multiple variables by passing variables by reference through their OUT parameter.4.Can you have two functions with the same name in a PL/SQL block ? Yes.5.Can you have two stored functions with the same name ? Yes.6.Can you call a stored function in the constraint of a table ? No.7.What are the various types of parameter modes in a procedure ? IN, OUT AND INOUT.8.What is Over Loading and what are its restrictions ? OverLoading means an object performing different functions depending upon the no. of parameters or the data type of the parameters passed to it.9.Can functions be overloaded ? Yes.10.Can 2 functions have same name & input parameters but differ only by return datatype No.11.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, exceptions12.Why Create or Replace and not Drop and recreate procedures ? So that Grants are not dropped.13.Can you pass parameters in packages ? How ? Yes. You can pass parameters to procedures or functions in a package.14.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 15.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)

The use of Statement Level Trigger is auditing pops into my head immediately. moredetailed security enforcement (prevent the update from happening between 9am and 5pm for example). notification (after trigger - generate an alert to let someone know the data changed). mutating table work arounds (you can read and write the table the trigger fired on in statement triggers).

16.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. 17.What is the maximum no. of statements that can be specified in a trigger statement ? One. 18.Can views be specified in a trigger statement ? No 19.What are the values of :new and :old in Insert/Delete/Update Triggers ? INSERT : new = new value, old = NULL

Page 1

Page 2: Oracle Questions

Oracle_Questions DELETE : new = NULL, old = old value UPDATE : new = new value, old = old value 20.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 triggersare said to be cascading. Max = 32. 21.What are mutating triggers ? A trigger giving a SELECT on the table on which the trigger is written. 22.What are constraining triggers ? A trigger giving an Insert/Update on a table having referential integrity constraint on the triggering table. 23.Describe Oracle database's physical and logical structure ? Physical : Data files, Redo Log files, Control file. Logical : Tables, Views, Tablespaces, etc. 24.Can you increase the size of a tablespace ? How ? Yes, by adding datafiles to it. 25.Can you increase the size of datafiles ? How ? No (for Oracle 7.0) Yes (for Oracle 7.3 by using the Resize clause --- Confirm !!). 26.What is the use of Control files ? Contains pointers to locations of various data files, redo log files, etc. 27.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 28.What are the advantages of clusters ? Access time reduced for joins. 29.What are the disadvantages of clusters ? The time for Insert increases. 30.Can Long/Long RAW be clustered ? No. 31.Can null keys be entered in cluster index, normal index ? Yes. The index key length is a function of your blocksize - about 40% of the size of theblock. you have a 2k block, small key length. 32.Can Check constraint be used for self referential integrity ? How ? Yes. In the CHECK condition for a column of a table, we can reference some other column of the same table and thus enforce self referential integrity. 33.What are the min. extents allocated to a rollback extent ? Two 34.What are the states of a rollback segment ? What is the difference between partly available and needs recovery ? The various states of a rollback segment are : ONLINE, OFFLINE, PARTLY AVAILABLE, NEEDS RECOVERY and INVALID. 35.What is the difference between unique key and primary key ? Unique key can be null; Primary key cannot be null. 36.An insert statement followed by a create table statement followed by rollback ? Will the rows be inserted ? No. 37.Can you define multiple savepoints ? Yes. 38.Can you Rollback to any savepoint ? Yes. 40.What is the maximum no. of columns a table can have ? 254. 41.What is the significance of the & and && operators in PL SQL ? The & operator means that the PL SQL block requires user input for a variable. The && operator means that the value of this variable should be the same as inputted by the user previously for this same variable. If a transaction is very large, and the rollback segment is not able to hold the rollback information, then will the transaction span across different rollback segments or will it terminate ? It will terminate (Please check ). 42.Can you pass a parameter to a cursor ? Explicit cursors can take parameters, as the example below shows. A cursor

Page 2

Page 3: Oracle Questions

Oracle_Questionsparameter can appear in a query wherever a constant can appear. CURSOR c1 (median IN NUMBER) IS SELECT job, ename FROM emp WHERE sal median; 43.What are the various types of RollBack Segments ? Public Available to all instances Private Available to specific instance 44.Can you use %RowCount as a parameter to a cursor ? Yes 45.Is the query below allowed : Select sal, ename Into x From emp Where ename = 'KING' (Where x is a record of Number(4) and Char(15)) Yes 46.Is the assignment given below allowed : ABC = PQR (Where ABC and PQR are records) Yes 47.Is this for loop allowed : For x in &Start..&End Loop Yes 48.How many rows will the following SQL return : Select * from emp Where rownum < 10; 9 rows 49.How many rows will the following SQL return : Select * from emp Where rownum = 10; No rows 50.Which symbol preceeds the path to the table in the remote database ? @ 51.Are views automatically updated when base tables are updated ? Yes 52.Can a trigger written for a view ? No 53.If all the values from a cursor have been fetched and another fetch is issued, the output will be : error, last record or first record ? Last Record 54.A table has the following data : [5, Null, 10]. What will the average function return ? 7.5 55.Is Sysdate a system variable or a system function? System Function 56.Consider a sequence whose currval is 1 and gets incremented by 1 by using the nextval reference we get the next number 2. Suppose at this point we issue an rollback and again issue a nextval. What will the output be ? 3 56.Definition of relational DataBase by Dr. Codd (IBM)? A Relational Database is a database where all data visible to the user is organizedstrictly as tables of data values and where all database operations work on these tables. 57.What is Multi Threaded Server (MTA) ? In a Single Threaded Architecture (or a dedicated server configuration) the database manager creates a separate process for each database user. But in MTA the database manager can assign multiple users (multiple user processes) to a single dispatcher (server process), a controlling process that queues request for work thusreducing the databases memory requirement and resources. 58.Which are initial RDBMS, Hierarchical & N/w database ? RDBMS - R system Hierarchical - IMS N/W - DBTG 59.Difference between Oracle 6 and Oracle 7 ORACLE 7 ORACLE 6 Cost based optimizer · Rule based optimizer Shared SQL Area · SQL area allocated for each user Multi Threaded Server · Single Threaded Server Hash Clusters · Only B-Tree indexing

Page 3

Page 4: Oracle Questions

Oracle_Questions Roll back Size Adjustment · No provision Truncate command · No provision Database Integrity Constraints · Provision at Application Level Stored procedures, functions packages & triggers · No provision Resource profile limit. It prevents user from running away with system resources · No provision Distributed Database · Distributed Query Table replication & snapshots· No provision Client/Server Tech. · No provision 60.What is Functional Dependency Given a relation R, attribute Y of R is functionally dependent on attribute X of R if and only if each X-value has associated with it precisely one -Y value inR 61.What is Auditing ? The database has the ability to audit all actions that take place within it. a) Login attempts, b) Object Accesss, c) Database Action Result of Greatest(1,NULL) or Least(1,NULL) NULL 62.While designing in client/server what are the 2 imp. things to be considered ? Network Overhead (traffic), Speed and Load of client server 63.What are the disadvantages of SQL ? Disadvantages of SQL are : · Cannot drop a field · Cannot rename a field · Cannot manage memory · Procedural Language option not provided · Index on view or index on index not provided · View updation problem 64.When to create indexes ? To be created when table is queried for less than 2% or 4% to 25% of the table rows. 65.How can you avoid indexes ? TO make index access path unavailable · Use FULL hint to optimizer for full table scan · Use INDEX or AND-EQUAL hint to optimizer to use one index or set to indexes instead of another. · Use an expression in the Where Clause of the SQL. 66.What is the result of the following SQL : Select 1 from dual UNION Select 'A' from dual; Error 67.Can database trigger written on synonym of a table and if it can be then what would be the effect if original table is accessed. Yes, database trigger would fire. 68.Can you alter synonym of view or view ? No 69.Can you create index on view No. 70.What is the difference between a view and a synonym ? Synonym is just a second name of table used for multiple link of database. View canbe created with many tables, and with virtual columns and with conditions. But synonym can be on view. 71.What is the difference between alias and synonym ? Alias is temporary and used with one query. Synonym is permanent and not used as alias. 72.What is the effect of synonym and table name used in same Select statement ? Valid 73.What's the length of SQL integer ? 32 bit length

Page 4

Page 5: Oracle Questions

Oracle_Questions 74.What is the difference between foreign key and reference key ? Foreign key is the key i.e. attribute which refers to another table primary key. Reference key is the primary key of table referred by another table. 75.Can dual table be deleted, dropped or altered or updated or inserted ? Yes 76.If content of dual is updated to some value computation takes place or not ? Yes 77.If any other table same as dual is created would it act similar to dual? Yes 78.For which relational operators in where clause, index is not used ? < , like '% ...' is NOT functions, field +constant, field || '' 79.Assume that there are multiple databases running on one machine. How can you switch from one to another ? Changing the ORACLE_SID 80.What are the advantages of Oracle ? Portability : Oracle is ported to more platforms than any of its competitors, running on more than 100 hardware platforms and 20 networking protocols. Market Presence : Oracle is by far the largest RDBMS vendor and spends more on R & D than most of its competitors earn in total revenue. This market clout means that you are unlikely to be left in the lurch by Oracle and there are always lots of third party interfaces available. Backup and Recovery : Oracle provides industrial strength support for on-line backup and recovery and good software fault tolerence to disk failure. You can also do point-in-time recovery. Performance : Speed of a 'tuned' Oracle Database and application is quite good, even with large databases. Oracle can manage 100GB databases. Multiple database support : Oracle has a superior ability to manage multiple databases within the same transaction using a two-phase commit protocol. 81.What is a forward declaration ? What is its use ? PL/SQL requires that you declare an identifier before using it. Therefore, you mustdeclare a subprogram before calling it. This declaration at the start of a subprogram is called forward declaration. A forward declaration consists of a subprogram specification terminated by a semicolon. 82.What are actual and formal parameters ? Actual Parameters : Subprograms pass information using parameters. The variables orexpressions referenced in the parameter list of a subprogram call are actual parameters. For example, the following procedure call lists two actual parameters named emp_num and amount: Eg. raise_salary(emp_num, amount);

Formal Parameters : The variables declared in a subprogram specification and referenced in the subprogram body are formal parameters. For example, the following procedure declares two formal parameters named emp_id and increase: Eg. PROCEDURE raise_salary (emp_id INTEGER, increase REAL) IS current_salary REAL; 83.What are the types of Notation ? Position, Named, Mixed and Restrictions. 84.What all important parameters of the init.ora are supposed to be increased if you want to increase the SGA size ? In our case, db_block_buffers was changed from 60 to 1000 (std values are 60, 550 &3500) shared_pool_size was changed from 3.5MB to 9MB (std values are 3.5, 5 & 9MB) open_cursors was changed from 200 to 300 (std values are 200 & 300) db_block_size was changed from 2048 (2K) to 4096 (4K) {at the time of database creation}. The initial SGA was around 4MB when the server RAM was 32MB and The new SGA was around 13MB when the server RAM was increased to 128MB. 85.If I have an execute privilege on a procedure in another users schema, can I execute his procedure even though I do not have privileges on the tables within the procedure ?

Page 5

Page 6: Oracle Questions

Oracle_Questions Yes 86.What are various types of joins ? Equijoins, Non-equijoins, self join, outer join 87.What is a package cursor ? A package cursor is a cursor which you declare in the package specification withoutan SQL statement. The SQL statement for the cursor is attached dynamically at runtime from calling procedures. 88.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. 89.What are the various types of queries ? Normal Queries Sub Queries Co-related queries Nested queries Compound queries 90.What is a transaction ? A transaction is a set of SQL statements between any two COMMIT and ROLLBACK statements. 91.What is implicit cursor and how is it used by Oracle ? An implicit cursor is a cursor which is internally created by Oracle. It is createdby Oracle for each individual SQL. 92.Which of the following is not a schema object : Indexes, tables, public synonyms, triggers and packages ? Public synonyms 93.What is the difference between a view and a snapshot ? 94.What is PL/SQL? PL/SQL is Oracle's Procedural Language extension to SQL. The language includes object oriented programming techniques such as encapsulation, function overloading, information hiding (all but inheritance), and so, brings state-of-the-art programming to the Oracle database server and a variety of Oracle tools. 95.Is there a PL/SQL Engine in SQL*Plus? No. Unlike Oracle Forms, SQL*Plus does not have a PL/SQL engine. Thus, all your PL/SQL are send directly to the database engine for execution. This makes it much more efficient as SQL statements are not stripped off and send to the database individually. 96.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' 97.Can one read/write files from PL/SQL? Included in Oracle 7.3 is a UTL_FILE package that can read and write files. The directory you intend writing to has to be in your INIT.ORA file (see UTL_FILE_DIR=... parameter). Before Oracle 7.3 the only means of writing a file was to use DBMS_OUTPUT with the SQL*Plus SPOOL command. DECLARE fileHandler UTL_FILE.FILE_TYPE; BEGIN fileHandler := UTL_FILE.FOPEN('/home/oracle/tmp', 'myoutput','W'); UTL_FILE.PUTF(fileHandler, 'Value of func1 is %s\n', func1(1)); UTL_FILE.FCLOSE(fileHandler); END;98.How can I protect my PL/SQL source code? PL/SQL V2.2, available with Oracle7.2, implements a binary wrapper for PL/SQL programs to protect the source code. This is done via a standalone utility that transforms the PL/SQL source code into portable binary object code (somewhat larger than the original). This way you can distribute software without having to worry about exposing your proprietary algorithms and methods. SQL*Plus and SQL*DBA will

Page 6

Page 7: Oracle Questions

Oracle_Questionsstill understand and know how to execute such scripts. Just be careful, there is no "decode" command available. The syntax is: wrap iname=myscript.sql oname=xxxx.yyy 99.Can one use dynamic SQL within PL/SQL? OR Can you use a DDL in a procedure ? How? From PL/SQL V2.1 one can use the DBMS_SQL package to execute dynamic SQL statements. Eg: CREATE OR REPLACE PROCEDURE DYNSQL AS cur integer; rc integer; BEGIN cur := DBMS_SQL.OPEN_CURSOR; DBMS_SQL.PARSE(cur,'CREATE TABLE X (Y DATE)', DBMS_SQL.NATIVE); rc := DBMS_SQL.EXECUTE(cur); DBMS_SQL.CLOSE_CURSOR(cur); END; 1. What is Referential Integrity rule? Differentiate between 2. Delete & Truncate command. 3. Implicit Cursor & Explicit Cursor. 4. Ref. key & Foreign key. 5. Where & Having Clause. 6. What are various kinds of Integrity Constraints in Oracle? 7. What are various kind of joins? 8. What is Raise_Application_Error? 9. What are various kinds of exceptions in Oracle? 10. Normal Forms

Oracle Notes :

Oracle 8i - It is a DB of internet computing , It changes the of information managed and accessed to meet the demandof internet age. -- Significant new feature for OLTP(Online trans Processing) and data ware housing Appl. --To mange all types of datain web site. -- iFS Internet file Syatem -- interMedia to manage and access multimedia data,audio,video -- Support to java(to install JVM on server) -- Security enhancement(authentication and authorization,centralizing user management)

Oracle 8(ORDBMS) - -Parrallel enhancement ,faster connection -Table partitioning , Connection inc to 30000 ,Table column upto 1000 -DB size inc from few tera byte to 10 tera. , Data file inc 65,533 -Support MTS,provides LOB

Oracle Start - 1. Oracle instance start -Allocates SGA and start BAckground processes. 2. Mount Oracle DB-Method of Associating DB with previous started instance 3.Opening DB-To make available.

Normalization - It's a technique thr. which we can design the DB. During normalization dependanciescan be identified which can cause pbs during deletion & updation .It is used in simplifing the structure of table. 1NF-Unnorma;ised data transfer to normalised form.

Page 7

Page 8: Oracle Questions

Oracle_Questions 2NF-Functional dependancies can be find out & decompose the table without loss of data. 3NF-Transist dependancies ,Every non key attrbute is functionally dependant on justPK. 4NF(BCNF)-The relation which has multiple candidate keys ,then we have to go for BCNF. Denormalization- At the same time when information is required from more than one table at faster rate then it is wiser to add some sort of dependancies.

Rooling Forward -To reapply to Data file to all changes that are recorded in Redo log file due to which datafile contains commited & uncommited dat. Forward Declaration-To declare variable and procedures before using it. 2- Tier Arch. Disadv-When Business Rule changes. PL/SQL Record-To represent more than one row at time. PL/SQL Table -To define single variable comprises several data element. To delete define one more empty table and assign it. Tablespace - Profile-To control system resources ,memory ,diskspace and CPU time. We can find rows effected by %rowcount. Data Binding-Dividing the cursor in appl as per select stamt. Truncate -Faster than delete ,doesn't fire ny DB trigger ,Allocate space ,No rollback. Defered Integrity constraints-When we refere PK in the same table where we defined . Cascading trigger- Temporary Table-Delete operation table. Log Table-to store information abt error. Coordinity- Err Trap -To trap error use SQLERRM,SQLCODE Modularity-PL/SQL allows to create program module to improve software reliability and to hide complexity Positional and Named Notation - The actual arguments are associaed with formal arguments by position k/s Positional Notation.It's commonly used. A Trigger doesn't accept argument & have same name as table or procedure as it exist in seperate namespace. How we ref FK in Sql -Join Condition. Security/Lock- Shared/exclusive -When 2 transaction wants to read/write from db at the same time. Dead- 1trans updates emp and dep 2 trans update dep and emp TO add a not null column to a table which has already some records - Alter table a Add(b number default 1 not null) Sequence- Start with,increment by,Cache/No cache,Order/No order,Max,Min ER Dia.- Entity Relation Dia. Set Transaction -To set a current transaction online offline Oracle err- ORA-06500 stiorage err ORA-00923 from keyword not found ORA-06501program err ORA-00904 Invalid Col ORA-00001Uk violated. Dynamic Sql -Which uses late binding File I/O-To read and write dat to and from text file thr. Oracle procedure. Joins-Equi,Non EQui,Self,inner joins,outer joins Index-16 col per table. Parsing-Syntax checking. Optimization-Use of index (HINT) Corelated Subquery -Which fires only once/ per row for entire stmt.

Page 8

Page 9: Oracle Questions

Oracle_Questions Simple Query--Which fires everytime for entire stmt Packages- Encapsulation,Overloading,improve performance as I/O reduces. PL/SQL Signature Method- To determine when remote dependant object get invalid. Object Previledge - On a particular object- I/U/D/Exec System Previledge -Entire collection object -C/A/D SGA Comprises -Data Buffer, Redo Log Buffer,Shared pool Buffer. Shared Pool - Req to process unique SQL stmt submitted to DB. It contains information such as parse tree and execusion plan . PGA -A memry buffer that contains data and control information for a server process. Dedicated server - Handles request. for single user. Multithresd Server-Handles request. for multiple user. Background process -DBWR,LGWR,PMON,SMON,CKPT DBWR-Writes modified data blocks from DB buffer to data file. LGWR- CKPT-Responsible to check DBWR and update control file to indicate most recent CKPT. SMON-Instance recovery at start up,Clean Temporary. Segment. PMON-Responsible for process recovery and user process fails,Cleaning up cache ,freeing resources which was using process. Segment-Data/Index/Rollback/Temp Data Dictionary -V$SESSION, information abt integrity constraints,space allocated for schema object. USER_TAB_COLUMNS gives you a list of tables as per Column. EOD Procedure-

Mutating/Constraining Err/Table Diff of where and group by Connect,Allocate.Analyse Command. Queries-- 1. 3rd Max select distinct sal from emp a where 3=(select count(distinct sal) from emp b where a.sal= 2. Delete Duplicate rows Delete Emp where rowid not in(select max(rowid) from emp group by emp_no) 3. First 5 Max No select sal from (select abs(-sal) sal from emp group by -sal) where rownum<6 Views-- -No Aggr function,group by,having -U/D without PK but not Insert. -Join -No DML -No join-DML Index -are used for row selection in where and order by only if indexing on column

You can launch the DBA Studio or the individual tools directly from the Windows NT Start menu. Or, you can use the following syntax to launch them from a command line prompt:

oemapp tool_name

where tool_name may be dbastudio, instance, security, storage, schema, or worksheet, if installed.

DBMS_ALERT is a Transaction Processing Package while DBMS_PIPE is an Application Development package

Developed By Aravindha Vaguleyan

DBA—

If to_date(sysdate,'DAY')='Tuesday' then .. Buffer Cache-To improve data block recently used by user in order to improve the

Page 9

Page 10: Oracle Questions

Oracle_Questionsperformance. Ordinality-Emp, Expences-Emp may expense sheet and Expense sheet has only one Emp. This fact k/s Referred Ordinality. Three Steps in creating DB.-- -Creating physical location for data in tables and indexes to be stored in DB. -To create the file that still store log entries. -To create logical structure of data dictionary. This is accomplished by create DB 1. Back up existing DB. 2.Create or Edit the init.ora file 3.Varify the instance name 4. Start Application management DB tool. 5.start instance 6.Create and Backup the new DB. Control file -250K Oracle Administration Assistant for W-NT is a DB management tool that enables to create DB administartor, operator, Users and role. To manage Oracle DB services, DB start up, shut down, Edit registry parameter setting, views oracle process information. Database Configuration Assistant -To create DB Oracle environment- OLTP-Many users can read and update, hight response time. DSS-Read only. Hybrid-both OLTP & DSS App. are running with this App. Init.ora-is a parameter file like DB_NAME, CONTROL_FILE, DB_BLOCK _SIZE RowID-BlockIDRowIdDatafileId Cluster Segment-To support use of cluster on the DB. Hash Cluster-By placing data in close proximity k/s Hashing. Optimization- Decides line of execution of query. First apply condition and then make Cartesian product. The cost can reduce by reducing no of rows. Oracle ways for optimization- -Evaluation of expression and condition amt 500/100--amt5 Like convert to equal IN - OR condition Any -OR Between/ALL -AND NOT-Avoid Transitivity-where a.id=b.id and a.id=1 use a.id=1 and b.id =1 Merging views Index column be in order by clause.

Bitmap Index- If the column has very few distinct entries We have to specify in init.ora Rate, Cost Choose mode based Approach -Avoid full table scan. -Access by Rowid -No function on Index column as it prevents the optimization. -Avoid IN, NOT and LIKE operator. -Column in where clause should be indexed. DATABASE- Profile -To control system resources like memory, diskspace, and CPU time. Role -Collection of privileges. Type of segment- Rollback, Temp, Data, Index Snapshot-It's a read only table, to improve efficiency of query, which referred remote db, therefore reduce remote traffic. DB trigger-is a PL/SQL block that are associated with given table. Diff bet Trigger and Procedure- -Trigger need not required to be call (Implicitly fire on event) -No TCL used -Proc/fun can be used in trigger -No use of Long raw,LOB,LONG

Page 10

Page 11: Oracle Questions

Oracle_Questions -Procedure is prefered over trigger as proc stored in compile form as trigg p_code stores. TO check time nbetwen 8 am and 6 pm. Create or replace trigger ptpt before insert on batch for each row declare A varchar2 (20); begin Select substr (to_char (sysdate,'HH: MI: SSSS’) 1,2) into a from dual;

If (a between '08' and ‘18’) then Raise_application_error (-20001,'Invalid Time'); End if; End; Snapshot too old-We have to refresh the snapshot Alter snapshot as Select * from [email protected] Refresh after seven days. We can reduce network traffic- -By using snapshot -By storing related table in same tablespace -By avoiding Row chain. Oracle DB uses three types of file structure. Data files-store actual data for tablespace, which is a logical unit of storage. Every tablespace has one or more data file to store actual data for tables, indexes, and clusters. Data is read and write to data file as needed. Redo log file-Two or more redo log file make up a logical redo log, which is used to recover modifications that have not been written to data files in event of power outage. Control file-Used at start up to identify the DB and determine which redo log file and data file are created. 1 data file, 1 control file, 2 redo log file. SET TRANSACTION-We use set transaction statement to login a read only or read-write or to assign the current transaction to specified rollback segment. Where date=sysdate-daily sale sysdate-7 weekly sale sysdate-30 monthly sale. A function must contain atleast one return value else PL/SQL raises predefined exception program_error. Actual parameter- when call Formal parameter Parametric Cursor - The cursor in which we can pass value when it is being opened Sql Stmt Execu- -Reserves an area in memory called Private Sql Area. -Populate this area with app. data. -Process data in memory area. -Free the, memory area when exec is complete. Active set- A set of rows return by a mult-row query. Export-Putting data of tables in file, which can be, handles by OS. Auditing- is used for noting down user's activity and statistics abt the operations in data objects. The auditing are 1-Stmt 2-Preveledge 3-Object 1-It is done to audit stmt activity .The auditing information abt. date & time of information, nature of operation is stored in table AUD$ which is used by user sys. Audit select on itemmaster; Then app. auditing is done and stored in table .

Page 11

Page 12: Oracle Questions

Oracle_Questions -To record the usage of privilege -To record the activity on object. Nature of Auditing- Auditing is done on -Per session basis-one record is generated. Per statement basis per session/stmt Audit any allows user to audit any schema object in the DB. Table partitioning- Table partitioning divides table data between two or more tablespaces and physical data file on separate disk. We can use it to improve transaction throughout and certain type of queries for large tables. Restriction- -A table that is a part of cluster can't be partioned. -A table can be partitioned based on ranges column values only. -Attribute of partitioned table can't include long, long raw or any lob data type. -Bitmap indexes can't be defined on partioned tables. We add partition using ALTER TABLE OR Create table aa ( a date, B number C varchar2 (10)) partion by range(a,b) (partition pa1 values less than ('01-jan-99', 2) tablespace tsp1, -----------------------------------); Accessing partition table- Select * from aa partion(pa1); Drop partion -Alter table AA drop partion pa1;

SQL Language Extension- Oracle * provide new built-in datatype, object datatypes, nested tables, and a no of other features that require new DDL extension. VARRAY REF LOBS Create table AA(a N (10) B date, C varchar2 (10));

Create type aa1 as varray (5) of number (5);

The UTLBSTAT and UTLESTAT script to get general overview of database 's performanceover a certain period of time. UTLBSTAT creates table and views containing cumulative database performance summaryinformation at the time when the script runs .All the objects create by UTLBSTAT contain word login. Utlbstat.sql

UTLESTAT creates table and views containing cumulative database performance summaryinformation at the time when the script runs .All the objects create by UTLESTAT contain word end. UTLESTAT spools the results of these SQL statements to a file called REPORT.TXT Utlestat.sql

Determine the shared Pool Performance.

The shared pool is one of the memory structures in SGA .It is comprised of the datadictionary and the library cache. Check v$sgastat The data dictionary cache buffers data dictionary objects that contain data about tables, indexes, users and all other objects. The Library Cache/SQL Cachebuffers previously executed queries, so that they need not be reloaded and reparsed if user calls them again.

Page 12

Page 13: Oracle Questions

Oracle_Questions

Otherwise if the information is not in the buffer then oracle must get it from disk.

The V$LIBRAY CACHE View stores performance data for library cache and V$ROWCACHE view stores performance data for the data dictionary cache.

Sometime we may have to increase the value of initialization parameter SHARED_POOL_SIZE. To improve the performance .

Redo Log --

Oracle 8 stores all changes to the database, even uncommitted changes, in the redo log files. LGWR writes .

Alter database archievelog

Edit the parameter initialization file. Log_archieve_start =true -turn it on Log_archieve_dest=c:/oracle/ora81/archieve -location log_archieve_format="ARCH%S.LOG" - name format for archieve file . %S for log sequence number .

By querying the V$SESSION view , we can determine who is logged on ,as well as information such as the time of logon .

Kill a session - ALTER system kill session '&sid,&serial' Select Sid,serial#,status from V$session where username='name';

Unbalanced Index – if we do have lot on index on a table and we are doing I/U/D frequently then there is a problem of disk contention . To check this problem sees the BLEVEL value in DBA_INDEXES and if it is 1,2,3,4 then it’s ok else rebuild the index .

Alter index satish.a_satish rebuild unrecoverable ;

Comments on table and columns

--For documentation purpose . Comment table a is ‘table a’ ; Retrieve comment from user_tab_comment Comment column a. a is ‘column a’; user_col_comments

Detect the objects close to maximum extent Check in dba_seqment Detect row chainingand row migration in tables Row migration occurs when a database block doesn’t contain enough free space to accommodate an update statement .In that case server moves the row to another block and maintains a pointer to to new block in the row’s original block .when pctfree is0 Row chaining in contrast , occurs when no single db block is larger enough to accommodate a particular row . this is common when table contain several large data types. It will reside in multiple database blocks . An unpleasant side effect of both chaining and migration is that the oracle * server must read more than one db block to read a single row . solution – move rows to a temp table and then delete rows from original table and then insert it from temp table .

Execute utlchain.sql

Thanks - Orafaq.comPage 13

Page 14: Oracle Questions

Oracle_Questions

1. What is the difference between & and && ? Ans: This symbol is equal to Start command & is to Run SQL commands.

&& will start SQL PLUS script ie.. in the same directory.

2. How to issue DDL statements from forms? Ans: DDL statements can be issued using built-in form_ddl('create table x(a

date)');

3. How to change mouse pointer in forms?Ans:Using the built-in Set_application_property(cursor_style,busy);

4. How to eliminate duplicate rows from a table? Ans: Delete from table_name a where rowid > (select min(rowid) from table name b

where a.key_value=b.key_value);

5. Difference between base table block & multi record block & control block? Ans: Base table block is one which is created from single table.

Control Block is create from more than one table(Hence no base table). Any block which contains more than one record is multi record block.

6. In a block can we change no of records if so how ? Ans: Yes, go to that block properties window and change no of records fetched to

required no.

7. How to compare two items in a forms at the same time ? Ans: Use freeze/unfreeze to see the properties of two items at the same time.

8. How do you change color and label of a push button ? Ans: Label at runtime can be changed using set_item_property.

Colour cannot be changed.

9. How do you make navigation stay in the same block though the mouse is clicked onpush button of other block ?

Ans: Change the block property mouse navigation property false.

10. How to know which mouse has been clicked right or left ? Ans: Use the built in :system.mouse_button_pressed. It stores 1 for left and 2

for right.

11. What is call_form and new_form ? Ans: In call_form both the forms are active.

But new_form closes the orginal form.

12. Can system variables be assigned by the user ? Ans: Yes.

13. How do you set the color of the current record of a block ? Ans: Set the visual attribute using set_item_property.

14. For which type of item when_validate_record cannot be used ? Ans: If the item is not a base table item.

15. How many levels of triggers are their ? Ans: Three levels. They are form,block,item level.

16. How to halt processing of any oracle forms trigger ? Ans: Using form_trigger_failure.

Page 14

Page 15: Oracle Questions

Oracle_Questions

17. What is post_form and commit_form ?Ans:post_form writes the data to the database but does not make permanent the changes. In commit_form the data is committed to the database.

18. Can read/write be possible from pl/sql? Ans: using utl_file package but it has to be in your working directory.

19. What is the limit of pl/sql block how to find out ? Ans: Complied block max size is 64k and max code size is 100k.

select * from dba_object_size where name='procedure_name';

20. What triggers are created when we generate master detail block ? Ans: on-check-delete-master

on-populate-details on-clear-details

21. What is non-isolated,isolated,cascading delete option ? Ans: non-isolated :- master record cannot be deleted if detail records are

present isolated :- deletes master record even if child records are there cascading :-both master and detail record are deleted

22. What is the purpose of root window and how is it created ? Ans: Create a default window and name it root_window.root window always displays

the console for the current active form.

23. How do you use images and video in to database and what are its limitations? Ans: Using long raw data type we can store images.One table can have only one

long raw field.

24. What is mirroring of the items? Ans: Two items can be set in such a way that if a change is made in one the value

will be reflected in the second.

25. what are various categories of triggers? Ans: Block-processing-triggers.

Interface-event-triggers. Message-Handling-Triggers. Master_detail triggers. Naviginational_ triggers. Query_time triggers. Transactional triggers. Validational triggers. B I M M N Q T V.

26. Which trigger would get fired first when_validate_item or post_change?

Ans: Post_change trigger fires first.

27. What is function of system.trigger_item? Ans: It captures the name of the Button_pressed that causes the trigger to fire.

28. Select details of those persons whose sal is repeated.? Ans: select ename,sal from emp where sal in(select sal from emp group by sal

having count(sal)>1 );

29. What is an entity? Ans: An entity is defined as an object that exists and can be distinguishable

Page 15

Page 16: Oracle Questions

Oracle_Questionsfrom others. Eg:- All the customers in a bank defines an entity called customers.

30. What is normalisation? Ans: The process of breaking up of data and storing them in tables in order to

reduce the redundancy is referred as Normalisation.

* first normal form : moving data into separate tables where the data in each table is of a similar type,and giving each table a primary

key-a unique label or identifier.this eliminates repeating groups of data.* 2nd normal form : taking out data that's only dependent on a part of the key. 31. What is 3rd normal form?

Ans: The table should be in second normal form and each non-key attribute should be functionally dependent on primary key .

32. What is denormalization , multi valid-dependency ? Ans: Delibrate introduction of redunduncy for a highly improvised performance is

referred to as denormalization.

33. How to convert number to character ? Ans: Use to_char function.

34. What is stored query ? Ans: View definition is referred to as stored query.

35. When index will be activated ? Ans: When the statements where clause uses the columns of one or more

single-column indexes in equality condition,index will be activated.

36. How to disable index using select statement ? Ans: Omit equality clause in the select statement.

/*drop index indexname*/ this using ddl.

37. What is multiple index,cluster ? Ans: Creating index on combination of columns is multiple indexing.

Creating index on combination of columns is multiple clustering.

38. Diferentiate view and synonym. Ans: View is a database object that logically represents one or more database

tables. Synonym is a database object which represents a table (or view) with different name.

39. How many attribute can be maintained as primary key ? Ans: A table can have only one primary key. However a composite primary key can

contain a maximum of 16 columns.

40. What is the difference between unique and primary key ? Ans: Unique constaints designates a column or combination of column as a unique

key. /*no repetition but will accept null values*/.

41. What are pseudocolumns ? Ans: A pseudocolumn behaves like a table column, and is not actually stored in

the table. eg.,currval, nextval, level, rowid, rownum.

Page 16

Page 17: Oracle Questions

Oracle_Questions

42. How to alter sequence ? Ans: Use alter sequence t command.

43. How to copy structure from one table to another ? Ans: Use the command----Create table as select * from table where 1=2;

44. What is composite datatype ? Ans: A composite type has internal components that can be mainpulated

individually eg., record,table etc.,

45. What is an exception ? Detection and processing predefined and user defined errors are called as exception when exception is raised normal execution is stopped and the control is shifted to exception handling part.

46. what is pragma exception ? Pragams (also called "pseudoinstructions") are processed at compile time, not at run time. They do not affect the meaning of a programs they simply convey information to the compiler.

47. What are cursor attributes ? The explicit cursor has four attributes they are %found, %notfound, %isopen,%rowcount.

48. How many database triggers can be applied on a single table ? Triggers B.I.F.O.S / B.I.F.E.R ---etc.,

49. Difference between before and after trigger. As indicates before trigger is fired before each statement(insert,update,delete) processed. after statement is fired after the statement is processed.

50. What are the types of subprograms ? There are two types 1) Procedures and 2) Functions.

51. Differentiate procedure and stored programs ? A procedure is a subprogram that performs a specific action. Create procedure syntax is used to create it. Stored procedures are subprograms which are compiled seperately and stored permanently in the database and are ready to be executed.

52. What are advantage of stored subprograms ? Once compiled and stored in data dictionary those can be accessed by all user . These are stored as objects. One copy is sufficient for all users thus occupying space. They are stored in parsed and compiled form.

***outer join: it is a method of intentionally retrieving selected rows of one tablewhich doesn't match the rows of the other table.

##VIEW :ALLOW US TO HIDE THE COMPLEXITY OF THE QUERY.WITH VIEWS,YOU CAN EASILY TEST AND TUNE YOUR QUERIES SEPEARTELY FROM YOUR PROGRAMS.SINCE,VIEWS ARE OUR OWN SCHEMA OBJECTS ,THE SAME VIEWS CAN BE USED IN MANY DIFFERENTPROGRAMSDURING DEVELOPMENT,IT MAY BE CONVENIENT TO MAINTAIN YOUR VIEW DEFINITIONS AND YOUR PROGRAM LOGIC SEPARATELY.

Page 17

Page 18: Oracle Questions

Oracle_Questions** CURSOR VARIABLES :: C-POINTERS: A PLACE IN MEMORY CONTAINING THE ADDRESS OF THE ANOTHER AREA IN THE MEMORY. CURSOR REPRESENTS AN ADDRESS OF AN AREA IN MEMORY WHERE PL/SQL MAINTAINS INFORMATION ABOUT AN SQL STATEMENT.WE ACCESS SOME OF THIS INFORMATION BY REFERENCING THE CURSOR ATTRIBUTES.## A CURSOR VARIABLE : IS A CONSTRUCT SIMILAR TO A POINTER THAT POINTS TO A CURSOR ITSELF.LIKE ANY VARIABLE,A CURSOR VARIABLE CAN BE ASSIGNED DIFFERENT VALUES AT DIFFERENT TIMES.THE VALUES IN THIS CASE WILL BE THE REFERENCES TO DIFFERENT CURSORS.IN OTHER WORDS,WHILE CURSOR IS A static AREA IN MEMORY,CURSOR VARIABLE IS A dynamic POINTER TO STATIC CURSORS.a cursor variable can be passed as a parameter from one pgm to another,no matter where this pgms execute.

DECLARING A CURSOR VARIABLE: DECLARE A 'REF CURSOR' TYPE AND THEN DECLARE YOUR 'CURSOR VARIABLE' WITH THIS TYPE. SYNTX: TYPE ref_cursor_name IS REF CURSOR [RETURN {cursor_name%ROWTYPE |cursor_variable_name%ROWTYPE |record_name%TYPE |record_type_name |table_name%ROWTYPE}]; SYNTX:cursor_variable_name ref_cursor_name;

weak REF CURSOR: IF WE OMIT THE RETURN clause and therefore we did not restrict the result set of future query to any particular record type.the compiler willn't perform type compatibility check between the rows returned by a query and the receiving variable.IF AN INCONSITENCY IS DETERMINED AT RUNTIME ,PL/SQL WILL RAISE THE ROWTYPE_MISMATCH exception with an sql error code 6504.

strong REF CURSOR: TYPE DIRECTS THE COMPILER TO VERIFY THAT THE TYPE OF ROWS RETURNED BY THE QUERY IS COMPATIBLE WITH THE TYPE SPECIFIED IN THE RETURN CLAUSE.53. Write the difference between function and stored function ? A function is a subprogram that computes a value. Functions have a return value. A stored function is a subprogram which are compiled seperately and stored permanently the database and are ready to be executed.

54. What are parameters modes in pl/sql ? Parameter define the behaviour of formal parameters there are in them a (default) , out, inout.

55. Advantages of using packages ? ARE SPECIAL CONSTRUCTS THAT COMBINE DIFFERENT COMPONENTS INTO ONE PROGRAM UNIT.

56. What is owner ship and view ship ? In owner ship view all form objects are visible and correspond to the hirerarchy of form_block_item .In this items & relations are owned by blocks.Locks are owned by forms.Triggers are owned by Forms,blocks,items,all other items are owned by forms.View_Ship:-In this only Windows,canvas,views & items are displayed.

57. How to create a block using two tables? Create a View with two tables & select the view as base table for that block.

58. Differnciate when-event-trigger & on_event-trigger? When_event signals a point at which you can augement oracle default processing with additional operations or tasks. An On-event signals a point at which you can replace oracle forms default processing

59. What is On-close trigger?Page 18

Page 19: Oracle Questions

Oracle_Questions Fires when an operator or the application causes a query to close.

60. What is pre-query & post-query? These triggers are used to control query processing. Pre-query fires during execute query or count query processing, just before oracle forms constructs and issues the select statement to identify rows that match the query criterin. When a query is open in the block,the post_query trigger fires each time. Oracle forms fetches a record into a block. The trigger fires once for each record placed on the blocks last of records.

61. Differnciate When-validate-item & post-change? Fires during the validate the item process. Specifically, it fires as the last part of the item validation for items with the new or changed validation statuspost-change fires.

62. what is On-count trigger? Fires when oracle forms would normally perform default count Query processing to determine the number of rows in the database that match the current query creteria.

63. What is a system variable? Oracle forms provides system-built in system variables that keep track of run time status variables in any from trigger or user-name subprograms.

64. How many types of parameters are there? Three ie.. In, Out,Inout

65. Differnciate call-form,open-form,new-form. Open-form:-when a new form invoked using open-form the 1st form is active and both forms are navigable. New-form --Completly closes old form & new form is opened. Call-form--When one form invokes another from then first from is disabled & secured form is active.First form can be active only when called form is exited.

66. What is the difference between LOV & record group? LOV is list of values attached to text item.Each LOV should be based on the record group. LOV displays records stored in the underlying record group. Record group can be populated using the fixed values or by query.

67) How many types of menus are there? Two types 1)Default menu 2)custom menu

68. What is menu parameters ? For a menu that will be run in full-screen display style, you can associate a substitution parameter with a specific menu, rather than with an individual menu item. When a parameter is associated with a menu, Oracle forms prompts for the parameter value when the operator navigates to that menu, without waiting for operator to select a specific item on the menu.

69. What is copy procedure ? The copy procedure assigns an indicated value to an indicated variable or item. Standard pl/sql assignment, however, using the copy procedure allows you to indirectly reference the item whose value is being set.

70. What is a alert and what are its types ? An alert is a modal window that displays a message notifying the operator ofsome application condition. Three alert styles are there stop, caution , note these are used to convey action severoty.71. What is a Library ? A Library is a collection of subprograms, including user-named procedures, functions, and packages. Libraries provide a convenient means of storing client-side

Page 19

Page 20: Oracle Questions

Oracle_Questionsprogram units and sharing them among multiple applications.There are three library file formats .PLL, .PLX, .PLD..PLL-------The library .pll file contains both library source code and the compiled,platform-specific p-code (executable code). The .pll file is created or updated whenyou save your library module. In addition, when you save your library module, the changes are reflected in each module to which the library is attached..PLX-------The Library .plx file is a platform-specific executable that contains no source . If you want generate a version of your library that contains only the complied p-code, without any source this is used. The .plx file can only be generated from the command line..PLD-------The .pld file is a text format file, and can be used for source-controlling your library files.

72. What is RDBMS ? What are different data base models ? In RDBMS the data are stored in the form of tables i.e. rows and columns. Different database models are HDBMS, NDBMS,RDBMS.

73. What is sql ? SQL is stuctured query language. It is a non-procedural language that is written in english.

74. what is a transaction ? Transaction is a piece of logical unit of work done between two succesive commits or rollback.

75. What is commit ? Commit is TCL statement to make changes permanent into the database.``176. What is rollback ? It is a statement(TCL) which undoes all changes till a savepoint or to begining of transaction.

77. What DDL ? Statements used to define or alter user defined objects like tables,views etc (CAD).

78. What is DML ? It is a set of statements used to manipulate data . (SUDI).

79. What is a Lock ? To lock one or more tables in a specified mode. Lock manually overrides automatic locking and permits or denies access to a table or view by other users forthe duration of our operation.

80. What is deadlock ? When two user attempts to perform the actions that interfere with one another the situation is defined as deadlock.

81. What is shared lock ? If this type of lock is applied on a table then other users can query the table only.

82. What is an Exclusive lock? This mode of lock permits only query to other user & permits other user to enter into a lock on the same data.

83. What is share row-exclusive lock ? This mode allows others to look at the table but does not allow them to lockthe table in shared mode or updating mode.

84. What are group functions ? Function that are used to get summary information about a group or set of rows of a table.

Page 20

Page 21: Oracle Questions

Oracle_Questions

85. What is indexing ? Index is an ordered list of the contents of a column or group of columns of table.

86. What are clusters ? Cluster is a schema objects that contain one or more tables that have one ormore columns in common rows of one or more tables are stored together in the database.

87. What is a View ? View is like a window through which you can view or change information of a table. A view is also termed as virtual table.

88. What is a Rowid ? Rowid is address of each row contaning information about datafile, datablocketc.

89. What is data integrity ? What are its types ? A mechanism used by RDBMS to prevent invalid data entry into base tables.Entity integrity, referential integrity and general business rules.

90. What is referential integrity ? Enforces master / detail relationship between tables based on same server.

91. What are different datatypes ? Internal datatypes like Character, Date, Rowid, Raw, Longraw etc.,Composite datatypes like Table datatype, Record datatype.

92. What is varchar2, how is it different from char ? Varchar2 datatype specifies a variable length character string. Memory is saved if varchar2 is used. Do not use varchar2 if frequent updates are carried out.

93. What is a Null ? A data field without any value in it is called a null value.

94. What is a Sequence ? A sequence is a database object from which multiple user can generate uniqueintegers.

96. What is like operators ? How is it different from in operators ? Like operators is used in character string comparisions with pattern matching. In operator is used to perform eqality condition between two conditions.

97. What are single row number functions ? The type of functions that will return value after each row is processed

98. What are date functions? Function that operate on oracle dates are date functions.

99. What is new_time functions? Syntax new_time(DAB). This function returns date and time in a time zone.b and time zone.a and b are character expressions.

100. What is convert functions ? Convert function converts two different implementations of the same character set.eg., ---we8ph,L7dec,we6dec etc.

101. What is an expression ? An expression is a group of value and operatiors which may be evaluated as asingle function.

Page 21

Page 22: Oracle Questions

Oracle_Questions

102. What are different type of operators ? Logical operators, Compound operators, Arithematic operators, Negating operators.

103. What is a condition ? Condition is said to be of the logical datatype that evaluates to a true of flase value.

104. What are the forms of conditions ? A comparision with expression or sub query results.A comparisions with any or all members in a list or a subquery.A test for membership in a list or a subquery.A test for inclusion in a range.A test for nulls.A test for existence of rows in a subquery.A test involving pattern matching.A combination of ther conditions. **result set : is a set of rows returned by this query.**cursor : is a pointer to an area in memory allocated by an oracle instance in order to maintain information about executing the query.##select into stmt can cause 2 predefined exceptions: NO_DATA_FOUND,TOO_MANY_ROWS.105. What are cursors ? Oracle uses work areas called private Sql area to execute Sql statements & processing information.This private Sql work areas are known as Cursors.

106. What are Explict cursors? cursors defined to perform multiple row select are known as explict cursors.

107. What is a PL/SQl? It is a transcation processing language that offer procedural solutions.

108. What is Embebbed SQL? Sql statements written in a host language are known as embedded sql statements.

109. What are conditional constructs of pl/sql? Statements that are useful to have a control over the set of statements being executed as a single unit are called as conditional constructs. eg.,----then------elsif etc.

110. How to difine a variable in pl / sql ? Variable name datatype(size) not null := value ;

111. How to define a cursor in pl / sql ? Cursor variable is <query>.

112. What are exceptions ? The block where the statements are beinG defined to handle internal and userdefined pl/sql errors.

113. What are system exception ? When an oracle error is enconuntered pl /sql block raises an error by itself. Such errors are called as internal or system defined exception. eg.,-----zero divide, no data found, value error, too-many-rows.

114. What is a schema ? Schema is a logical collections of related items of tables and views.

115. What are profiles ? A profile is a file that contains information about the areas that a user

Page 22

Page 23: Oracle Questions

Oracle_Questionscan access.

116. What are roles ? A role is a collection of related privileges that an administrator can grantcollectively to database users.

117. How can we alter user password ? Syntax alter user user_name identified by passwd;

118. What is table space ? A tablespace is a partition or logical area of storage in a database that corrosponds to one or more physical data files.

119. What is an extent ? Extent is no of contignous block that oracle7 allocates for an object when more space is nessasary for the object data.

120. What are pctfree and pctused parameters ? pctfree controls how much of the space in a block is reserved for statementsthat update existing rows in a table. pctused is a percentage of used space in a block that triggers the databaseto return to the tables free space list.

121. What is a block in oracle ? The place where data is stored physically in an operating system is known asblock.

123. What is segment in oracle ? What are its type ? The place where the data is stored in the allotted tablespace are called as segments. Three types are 1)index segment, 2) rollback segment, 3) temporary segment, 4) bootstrap segment.

124. What is the use of the Rollback segment? It is a portion of a database that records the information of the actions that should be done under certain circumstances like transcation rollback read consistency.

125. What is Read consistency in Oracle? It is a process that ignores all changes by others in a table whenever it isqueried Set transaction read only.

126. What is SGA? The library Cache & Dictionary Cache makes up the shared pool .The shared pool combined with buffer cache make up the system global area.A library chache it stores the sql statements and pl/sql procedures.Dictionary cache holds dictionary information in memory.Buffer cache the place where the datas related to recently requested transaction is stored.

127. What are background process ? Server activity is divided as foreground and background processes foreground handles the request from the client. Background handles other specific request of the server like writing data etc.

128. What is system userid ? Whenever you create a database an userid is automatically created related with database administration connections. This userid is called system userid.

129. Sys userid ? it is a special account through which dbsdbs can execute special database dba connections.

Page 23

Page 24: Oracle Questions

Oracle_Questions

130. What is data dictionary ? It provides alll the information of database objects, privelages, etc.

131. What is sql dba ? Sql dba is a utility through which you can manage database system effectively.

132. What are database files ? The physical files of oracle are known as database files.

133. What is a log file ? The files that contains information about the information or recovery of oracle database at the event of system crash or load failure.

134. What is a control file ? A control is a small binary file containing all the system executable code named as oracle .def. It contains database name,log files, database creation.

135. What does an update statement do ? Updates rows in the table.

136. What is an instance ? Oracle instance is that which provides the mechanism for processing and controlling the database.

137. what is an instance? Oracle instance is that which provnides the mechanism for processing & controlling the database.

138. What is startup & shutdown? Startup is a process making the oracle database to be accessedby all users.There are three stages 1) start a new instance for the database.2) Mount the database to the instance.3) opening the mounted database.shutdown is a process making the oracle database unavailable for all users. Close database, dismount the database from the instance, terminate the instance.

139. What is two phase commit ? All database servers in a distributed database either commit or rollback allthe statements in a transaction.

140. What are snapshots ? A snapshot is a table that contains the results of query of one or more tables or views often located on a remote database.

141. what is a system variable ? System variable is a sql * forms variable that keeps track of some internal process of sql forms in state.

142. What are global variables ? Global variable is a sql forms variable that is active in any tirgger withina form and is active through out sql form session.

143. What are different type of objects in sql * forms ? Form, Block, Field, Pages, Triggers, Form-level-triggers.

144. What are pages ? Pages are collection of display information such as constant text and graphics. All fields are displayed in a page.

Page 24

Page 25: Oracle Questions

Oracle_Questions145. What is a block and what are its types ? Block is an object of forms that describes section of a form and server as adefault database inteface. Control block, detail block, master block, multi record block, not enterable block, single record block.

146. What is page zero ? The place where the hidden fields are placed in an application.

147. What does message procedure do ? The message procedure displays specified text on the message line.

148. What is array size parameter do ? The array size parameter is a block charecteristics that specifies the maximum number of records that sql forms can fetch form the database at one time.

149. How to send parameters to another form ? use global variables.

150. How to give automatic hint to form fields ? Set hint attribute in the property sheet for the fields to true.

151. How to rename a form ? By using rename option in the action menu.

152. What is a content canvas view ? A content canvas view ( or simply content view ) is the base view that occupies the entire content pane of the window in which it is displayed.

153. How can we change the tittle of my RUNFORM window ? Use set_window_[roperty(forms_mid_window,title,'your title');

154. How can I dynamically prevent the user from entering a new record ? Have a pre-record trigger that does :If ((dynamic-condition-is -true) and :system.record_status='New') thenRaise form_trigger_failure;end if;

155. How can I dynamically make an entire block query-only at runtime ? Issue the following :set_block_property('blockname',insert_allowed,property_off);

set_block_property('blockname',update_allowed,property_off);

156. If a timer expires during a long running query when is it handled ? The timer will always wait to be handled until the current operation has been completed. In other words, the query is completed before the timer is serviced.

--end of 1st set of questions---these are a bit high level and are elobrately explained.

1)select the nmae of managers who manage more than one employee.A)select mgr from emp group by mgr having count(*)>1;

2)select empno,ename,dno,dname,salary and the average salary of each department.A) select a.eno,a.ename,a.dno,a.sal ,avg(a.sal) from emp a,emp b where a.dno=b.dno group by a.dno,a.eno,a.ename,a.sal;3)write a query to delete duplicate rows.A)delete from emp where rowid in(select max(rowid) from emp where eno=1); Delete from emp where eno=1 and rowid !=(select max(rowid) from emp where eno=1;4)what are sql pseudo-columns.A)currval returns current value from a sequence. Level used in conect by clause returns 1 for root node and 2 for child

Page 25

Page 26: Oracle Questions

Oracle_Questionsnode. Rownum returns the number of the row Rowid returns the address of the row Sysdate returns current date and time. User returns the oracle user name . Id returns the oracle user id number which is unique and alloted by the system when a user is created.5)what is sql operator precedence.A)=,!=,<,>,<=,>=,between, in,like,is null.6)Find out first highest paid persons displaying their names and salaries ;A)select empno,ename,sal from emp a where &no >(select count(distinct sal) from emp Where sal>=a.sal);7)what is the difference between sql%found and c1%found.A)sql%found is used only in exception handling whereas c1%found is used after a fetch statement.8)How can you create or define and use a user_defined exception whose name is same as pre-defined exception declare no_data_found exception; Begin Action 1; Action 2; If no_data_found then Raise no_data_found; End if; Exception when standard.no_data_found then statements; when no_data_found then statements;end;

9)Write about snapshots.A)In order to improve the performance of an application that uses distributed data we can make local copies of remote tables.Oracle provides snapshots as a means of managing local copies of remote tables.Snapshot can be build using one or more tables/views from one or more remote databases. The refresh of the data will be taken care by Oracle as specified by parameters.In 7.0 snapshots were not updateable.

10)What is Two phase commit.A)Oracle manages distributed transactions with a special feature called two-phase commit.Two-phase commit guarantees that a transaction is valid at all sites by thetime it commits or rollbacks.All sites simultaneously commit or rollback what ever may be the error.

11)what is a role?A) A role is a collection of related privilages that an administrator can grant collectively to database users and other roles.

12)what is a distributed database.A)A distributed database is two or more physically seperate database that logically make up one database,users of any server can access information through out the database.

13) list all report triggers.A) Before report

Page 26

Page 27: Oracle Questions

Oracle_Questions After trigger Between pages Before parameter form After parameter form

14)Order of precedence of field level triggers.A)pre-text-item, when-new-item-innstance,key-next-item,when-validate-item Post-text-item.

15)what are different rdbms available in the market. A) Oracle,Ingries,Sybase,Unify,Informix,Foxpro.

16)What are different Gui 's A)MS-Windows,power builder,Dev 2000, VB,VC++ etc.

17)What is SGA? A) system global area which is the allocation of memory for Oracle in the

primary memory.

18)What is MDI?A)Multiple Document Interface.

19)Why is oracle choosen as RDBMS.(codd's rules) A) the information rule.

Guarentee access rule Systematic treatement of null values.Dynamic online catelouge based on the relational modelComprehencive Data sub language rule.View updating ruleHigh level insert,update and delete Physical data independence Logical data independenceIntegrity independenceDistribution independenceNon-sub rule. 20)What is Oracle optmizer? A)Oracle Optimizer is a part of the RDBMS Kernal which reads a query And decides on the best manner of executing the request based on the tables and indexes.

21)What is page 0 A)This is the address Oracle uses for the non display fields of the Form.

22)What is a correlated Query? A) A correlated query is a nested sub-query which is executed once for each

candidate row concidered by the main query.

23)What are different locks?A)Exclusive lock,shared lock, Row level lock,page level lock.

24)What are different indexes. A) unique indexes,composite indexes.

25)What are different clusters. A) indexed and hash clusters.

26)what is sqlcaA)strctured query language communication area.

27) what is sqlda A) strctured query language descriptor area.

Page 27

Page 28: Oracle Questions

Oracle_Questions

28------31 are blank.

32. What is OLTP ? On-Line Transaction Processing.

33. What is DCE ? Distributed Computing Environment.

34. What is API ? Application Program Interface.

35. Can you create tables from froms ? Yes, through forms_ddl (Create table emp(empno number, ename varchar2(22));

36. How to change the message of and Alert ? Set alert_message_property(alert,alert_message_text,new message);

37. Write a Sql statement to delete two identical rows with one statement . Delete from emp A where A.ename=X.ename and rowid in (select max (rowid) from emp where emp.ename=A.ename);

38. What are the triggers that are created by master_detail relationship ? On_Populate_Details On_Check_Delete_Master On_Clear_Details

39. What is master_detail relationship based on a single table called ? Self Referential Integrity.

40. Difference between & and && ? In & we can enter different records, where as in && we can enter the same records number of times by using '/ '.

41. If we are not using the keyboard will the Key-next-item trigger fires if not which trigger is suitable No, Post-next-item is suitable.

42. Number(*,2) will it work? Yes, It will take default 38 digits for *.

43. How do you attach a Menu to a Form? Create a form, go to form level properties & attach Menu file ie..PAYROLL.MMX TO MENU MODULE.

44. Based on the table given find the total amount of each sales person which should be more than the maximum amountTable :- Sname Amount A 4000 B 2000 A 200 C 3000 C 2000 B 200

Select sum(amount) from stable having sum (amount) > (select max (amount) from stable ) group by sname;

45. Difference between any and some. No difference.

46.What is PCTFREE ?Page 28

Page 29: Oracle Questions

Oracle_Questions It is a storage parameter you can use to minimize the row changing. It is the percentage of space free for updates.

47. To get sum of all salaries where in ename starts with same character say (A,B,P). Select substr (ename,1,1), sum (sal) from emp where substr (ename,1,1) in (select substr (ename,1,1) from emp ) group by substr (ename,1,1);

48. Difference between delete and truncate . Delete deletes the specified row only when the transaction is committed truncate deletes all the rows permanently without using commit.

49. What are the background processes created by Oracle ? Database Writer, Log Writer (LOGWRI) , Archiever (ARC) , System Monitor ( SYMON), Process Monitor (PMON), Check Point (CKPT), Dispatcher, Recoverer, and Lock

50. Will * work while creating a view with two tables using a join condition. No.51. What are different system attributes ? System.Cursor_Item System.Cursor_Block System.Cursor_Form System.Current_Item System.Current_Record System.Current_Value etc.,

51. What are different types of database triggers ? Statement levelBefore InsertAfter InsertBefore UpdateAfter UpdateBefore DeleteAfter Delete Row levelBefore InsertAfter InsertBefore UpdateAfter UpdateBefore DeleteAfter Delete

52. What are different methods of calling a form ? Open_Form, Call_Form, New_Form, and Call

53. What is Session ? It is the time limit that elapses between a user connecting to and disconnecting from a database instance.

54. What is Instance ? An instance is a collection of memory buffers.

55. Write a single SQL statement to find out the rows that are repeating. Select empno, count (*), ename from emp group by empno,ename having count (*) > 1;

56. Difference between procedure and function. Procedure executes an action where as function computes a value.

57. What is the default percentage of PCTUSED and PCTFREE in a table ?Page 29

Page 30: Oracle Questions

Oracle_Questions 60 and 40.

58. What is a Dirty Read ? When a transaction reads uncommitted data from another users uncommitted transaction.

59. List logical database structure organization of oracle. Tablespace, Schemas, Schema Object, Datablocks, Extents and Segments.

60. what are the phases of two_phase commit ? Prepare phase and commit phase.

61. What is Export / Import utility ? Export utility writes data from oracle database to OS files in oracle database format. Import utility reads data from OS files of oracle database format to database.

62. What is a trace file ? Whenever an internal error is detected by a process in oracle it dumps the information about the error into a trace file.

63. What are different types of database segments ? Data Segments. Index Segments. Rollback Segments. Temperory Segments.

64. Extensions of forms files. .FMX=============>FORM MODULE EXECUTABLE .FMT=============>FORM MODULE TEXT .FMB=============>FORM MODULE BINARY

65. Different types of master detail relationships in oracle . Non Isolated=========>Without deleting child cannot delete master.Isolated===========>Master record can be deleted without deliting child.Cascading======>With deletion of parent child records also get deleted.

66. How a user sets the relation properties at the run time ? By using set_relation property.

67. How do you retrieve current property of a relation ? Using get_relation property.

68. General types of master detail relationships. Master with dependent details Master with independent details. Details with two masters.

69. What are different procedures created by oracle ? Clear_All_Master_Details . Query_Master_Details. Check_Package_Failure.

70 How to load the data from a flat file which has duplicate rows in a oracle table which is a primary key ? By disabling the primary key.

71. Can we view the code used for creating a view. yes, by using All_Views.

72. what are the maximum number of columns defined per table ?Page 30

Page 31: Oracle Questions

Oracle_Questions 172 columns.

73. If we drop a table which has a synonym what happens to synonym ? Synonym will not be dropped and it will give error if it is accessed.

74. It is possible to create index on long column of a table ? No, it is not possible to create index on long column of a table.

75. What are the approaches used by oracle for Optimization ? Rule based Optimization and cost based Optimization.

76. what is Repository ? It is a dictionary of metadata.

77. What is delete set null option ? The child records are set to null when the dependent parent record is updated.

78. What is Schems ? The orginal database schema is created by writing a set of definations whichare translated by the DDL complier to a set of tables that are permanently stored in data dictionary.

79. What is parsing ? Parsing is the proccessing of a SQL statement to a cursor. At parse time several validation checks are made such as, do all referenced objects exist, are grants proper and is statement syntax correct. Also decisions regarding execution and optimization are made such as which indexes will be used.

80. What are different servers ? File Server Application Server Data Server Communication Server Database Server

81. What is three_tier Client / Server architechture ? One client and two servers (application and database servers).

82. What are different types of multi processing ? Symmetric and functional.

83. What are the built_in routines that are used for displaying a lov ? List_Values and Show_Lov.

84. What are different types of form triggers ?

Block Processing TriggersInterface Event TriggersMaster Details TriggersMessage Handling TriggersNavigational TriggersQuery Time TriggersTransaction TriggersValidation Triggers

List of Block Processing TriggersWhen_Create_Record

Page 31

Page 32: Oracle Questions

Oracle_QuestionsWhen_Clear_BlockWhen_Database_RecordWhen_Remore_Record

List of Interface Event TriggersWhen_Button_PressedWhen_Check_Box_ChangedWhen_Image_PressedWhen_Image_ActivatedWhen_Radio_ChangedWhen_Timer_ExpiredWhen_Window_ActivatedWhen_Window_ClosedWhen_Window_DeactivatedWhen_Window_Resized

List of Message Handling TriggersOn_Error and On_Message

List of Transaction TriggersOn_DeleteOn_InsertOn_LockOn_LogonOn_LogoutOn_UpdatePost_Database_CommitPost_DeletePost_Forms_CommitPost_UpdatePre_CommitPre_DeletePre_InsertPre_Update

List of Navigational TriggersPre TriggerPost TriggerWhen_New_Instance Triggers

85. How to trap success or failure of a built in routine ? By using Form_Success and Form_Failure.

86. List the built_in used for navigation between Independent forms. Go_Form Next_Form Previous_Form

87. How many long columns can be defined in a table ? Only one.

PL/SQL

88. What is the value of PL/SQL table index ? Boolean Integer.

89. PL/SQL Engine Oracle RDBMS Host Procedure PL/SQL Block

90. Features of PL/SQL. Variables and Constants=====> Number, Char, Date etc.,

Page 32

Page 33: Oracle Questions

Oracle_QuestionsSQL Support====================> Select, Insert, Update, Delete, Commit, Savepoint

and Rollback.Composite Datatype==============> Records, Rowtype etc.,Flow Control====================> If, Goto, Loop etc.,Built In functions=================>All SQL FunctionsCursor Management===============>Declare, Open, Fetch and CloseExceptions HandlingStored Code In Database

91. Advantages of PL/SQL Engine. It reduces network traffic.It reduces the processing time of the server

92. Scope of Objects . Scope of object is the region of the program over which tgat object may entially be used. The uobjects may be variables, cursors, user defined exceptions and constants. The scope of an object is the complete block in which it is declared.Including any sub_blocks nested within it. Objects declared in sub_blocks. However, are only available until that sub_block has ended .

SAMPLE :-

X NUMBER---------------------------------------------------------------------------------------------------------DECLARE Y NUMBERBEGIN ---------------------------------------- ----------------------------------------END;--------------------------------------------------------------------------------------------------------END;

93. Scalar Datatypes . These are datatypes that represents a single value. The main datatypes are those that correspond to column types in oracle tables.

Number--------------Maximum, precision is 38Varchar2------------Maximum Allowed is 32767Char-----------------Maximul Allowed is 265Boolean------------True or FalseDate----------------Ranges from 4712 B.C to 4712 A.D

94. Built -in functions of PL/SQL ? Single row numbe functions Single row character functions Datatype conversion functions (ex:- T0_char, To_Number etc) Date functions Miscellaneous functions like sqlcode, sqlerrm etc.,

95. Functions not available in PL/SQL ? Greatest Least Avg Min Max Count Sum Stddev Variance

Page 33

Page 34: Oracle Questions

Oracle_Questions

96. How can you write PL/SL structrual statements to scren(output) ? PL/SQL strutrual statements cannot directly write to the screen we can get the output through one of the following methods :-

· Write results to a table, then query the table after the block has run (OR)· Write results to a bind variable and use print command after the block has run (OR)· Call a procedure which outputs to the screen.

97. How do you call a PL/SQL stored procedure ? Procedure_name(parameter1, parameter2, parameter3,------------);ex., Clear_dept( 'Accounting' , True); (OR) Clear_dept(Delete department=>True, Department_name=>'Accounting' );

98. Are data defination language(DDL) commands allowed in PL/SQL . No.

99. What are different implicit cursor attribute ? · SQL%ROWCOUNT ====> Number of rows processed by the SQL statement(An integer

value) · SQL%FOUND ====>True if atlest one row was processed (A boolean

value) · SQL%NOTFOUND ====> tRUE IF NO ROWS WERE PROCESSED ( A boolean value)

These may be used in exception selection.

100. Explicit locking commands may also be inclued in a PL/SQL block. They are Table, Select..................for update of.

101. what are the different select cluses supported by PL/SQL ? Select item1, item2,------------- Into var1,var2,------------ From Table1, Table2,--------- [where condition(s)] [Group by item1, item2,----] [Having condition(s)] [For update of];

102. The %type attribute for one column/field . Identifier tablename.Column%typeex., V_Deptno Dept.deptno%type V_Loc Dept.Loc%type

103. What are different types of exceptions ? Predefined and user defined exceptions.

104. What are different predefined exceptions. Dup_Val_No_Index Invalid_Cursor Login denied No_Data_Found Invalid_Number Not_Logged_On Program_Error Storage_Error Timeout_On_Resource Two_Many_Rows Value_Error Zero_Divide Cursor_Already_Open Transaction_Backed_Out

Page 34

Page 35: Oracle Questions

Oracle_Questions

105. Composite Data types . The %Rowtype Attribute==>Used to declare a record based on table on table syntax :-Identifier Reference%RowtypeIdentifier Emp%Rowtype

106. User-Defined Records :- Define a type of record like Type type_identifier is record (field_name1 field_type [Not null] [:=value],Field_name2 field_type [Not null] [:=value].........);

107. Oracle uses work areas called private SQL areas to execute SQL statements and store processing information.

108. A select statement declared in the cursor gets executed at the time of opening the cusor.

109.Explicit cursor attributes. %FOUND True if latest fetch is successfull %NOTFOUND False if latest fetch is successfull %ROWCOUNT Returns the number of rows fetched %ISOPEN True if the cursor is currently open

110. Cursor and Records :- It is possible to define a record based upon the selected list of columns inan explicit cursor. This is convenient for processing the rows of active set, as youcan simply fetch into the record, and the value of row are loaded directly into the corresponding fields of the record.

EXAMPLE :- Declare Cursor c1 is select empno,sal,hiredate,rowid from emp where deptno=20 and Job='Analyst' for update of sal; Emp_record c1%rowtype; Begin Open c1; ` fetch c1 into emp_record;

The above example also shows the use of for update within the cursor query. This means that the rows returned by the query are locked exclusively when the open statement is obeyed. Since locks are realeased at the end of the transaction, you should not commit across fetches from an explicit cursor if for update is used.

111. Giving the where current of clause :- When referencing the current row from and explicit cursor, SQL commands may use the where current of clause giving the name of the cursor. This allows dates or deletes to be applied on a single row currently being addressed, without the need to explicitly reference rowid. For update should be used if where current of clause is used.

SAMPLE :- Fetch c1 into emp_record; If emp_record.ename='King' then Delete from emp where current of c1;

112. Cursor with Parameters :- Cursor identifier(parameter_name, data_type, parameter2 datatype,---) is query_expression.

SAMPLE :- Cursor c1(param1 number, param2 char) is select ename, sal, hiredatefrom emp where deptno=param1 and job=param2; open c1(30 'analyst');

113. Cursor for Loops :- Declare

Page 35

Page 36: Oracle Questions

Oracle_Questions Cursor cursor_name[(parameter)] is query_expression; Begin For record_name in cursor_name[(parameter)] Loop ---------------------------------------- ---------------------------------------- ---------------------------------------- end loop; end;-- end of 2nd set of questions.

This section is about triggers/procedures/functions.(examples and basic explanation).PL/SQL

It is the procedural extenstion of sql, PL stands for programming language. PL/SQL blocks combines the data manupluating power of sql with data procssing power of procedural language. PL/SQL block contains DML & TCL commands.

Advantages:- Without PL/SQL, oracle must process sql commands one at a time. But with PL/SQL the entire block of statements can be processed at a time. This help in improving performance.

Controlled Structures:- 1) Conditional control 2) Itrerative control 3) Sequential control

1) Conditional control:- a)If then b) If then else c) If then elsif

2) Iterative control:- a) Simple loop b) For loop c) While loop

3) Sequential control:- a) Goto statements

1) DECLARE ZZZ NUMBER(5);

BEGIN SELECT SAL INTO ZZZ FROM EMP WHERE EMPNO=7788; IF ZZZ > 2000 THEN UPDATE EMP SET SAL=ZZZ+10 WHERE EMPNO=7788;

END IF; END; /------------------------------------------------------------------------------------------------------2) DECLARE ZZZ NUMBER(5);

BEGIN SELECT SAL INTO ZZZ FROM EMP WHERE EMPNO=7788; IF ZZZ > 2000 THEN UPDATE EMP SET SAL=ZZZ+10 WHERE EMPNO=7788;

ELSE UPDATE EMP SET SAL=ZZZ+500 WHERE EMPNO=7788;

END IF; END;

Page 36

Page 37: Oracle Questions

Oracle_Questions /

3) DECLAREZZZ NUMBER(5);AAA NUMBER(5):=7788;BEGINSELECT SAL INTO ZZZ FROM EMP WHERE EMPNO=AAA;IF ZZZ > 2000 THENUPDATE EMP SET SAL=ZZZ+10 WHERE EMPNO=AAA;ELSEUPDATE EMP SET SAL=ZZZ+500 WHERE EMPNO=AAA;END IF;END;/--------------------------------------------------------------------------------

4) DECLARE AAA NUMBER; ZZZ NUMBER(5);BEGIN SELECT SAL INTO ZZZ FROM EMP WHERE EMPNO=&AAA; IF ZZZ > 2000 THEN UPDATE EMP SET SAL=ZZZ+10 WHERE EMPNO=&AAA;ELSE UPDATE EMP SET SAL=ZZZ+500 WHERE EMPNO=&AAA; END IF;END;/-----------------------------------------------------------------------------------------------------`5) DECLARE ZZZ EMP%ROWTYPE;BEGIN SELECT * INTO ZZZ FROM EMP WHERE EMPNO=7788; IF ZZZ.SAL > 2000 THEN UPDATE EMP SET SAL=ZZZ.SAL+10 WHERE EMPNO=7788;ELSE UPDATE EMP SET SAL=ZZZ.SAL+500 WHERE EMPNO=7788; END IF;END;/ ---------------------------------------------------------------

6) DECLARE A NUMBER:=10;

BEGIN LOOP A:=A+10; EXIT WHEN A=100; END LOOP; DBMS_OUTPUT.PUT_LINE(A);END;7) DECLARE A NUMBER:=10; BEGIN WHILE A<100 LOOP A:=A+10; END LOOP; DBMS_OUTPUT.PUT_LINE(A); END;8) DECLARE A NUMBER:=10; BEGIN FOR I IN 1..10 LOOP

Page 37

Page 38: Oracle Questions

Oracle_Questions A:=A+10; END LOOP; DBMS_OUTPUT.PUT_LINE(A); END;

9) BEGIN FOR I IN 1..5 LOOP INSERT INTO TEMPP VALUES(I); END LOOP; END;/------------------------------------------------------------------------------------------------------10) DECLARE I NUMBER:=1;

BEGIN WHILE I < 5 LOOP INSERT INTO TEMPP VALUES(I); I:=I+1; END LOOP; END; /------------------------------------------------------------------------------------------------------

11) BEGIN FOR I IN 1..5 LOOP INSERT INTO TEMPP VALUES(I,'IN FOR'); END LOOP;END;/12)DECLARE AAA NUMBER:=10;BEGIN FOR I IN 1..AAA LOOP INSERT INTO TEMPP VALUES(I,'IN FOR'); END LOOP;END;/13) DECLARE AAA NUMBER:=10; BBB NUMBER:=20;BEGIN FOR I IN AAA..BBB LOOP INSERT INTO TEMPP VALUES(I,'IF FOR'); END LOOP;END;/14)

DECLARE AAA NUMBER;BEGIN FOR I IN 1..&AAA LOOP INSERT INTO TEMPP VALUES(I,'IF FOR'); END LOOP;END;/

Page 38

Page 39: Oracle Questions

Oracle_Questions15)DECLARE AAA NUMBER:=10;BEGIN FOR I IN REVERSE 1..AAA LOOP INSERT INTO TEMPP VALUES(I,'REVERSE FOR'); END LOOP;END;/ ----------------------------------------------------------------------------------------

16) DECLARE AAA NUMBER:=10;BEGIN FOR I IN 1..AAA LOOP IF I=5 THEN AAA:=20; END IF; INSERT INTO TEMPP VALUES(I,'IN FOR'); END LOOP;END;/

17) DECLAREAAA NUMBER:=1;BEGIN WHILE AAA < 10 LOOP IF AAA > 5 THEN EXIT; END IF; INSERT INTO TEMPP VALUES(AAA,'IN WHILE'); AAA:=AAA+1; END LOOP; INSERT INTO TEMPP VALUES(999,'OUTSIDE WHILE');END;/ -------------------------------------------------------------------------------

18) DECLARE AAA NUMBER:=1;BEGIN WHILE AAA < 10 LOOP IF AAA=5 THEN GOTO MYPROC; END IF; INSERT INTO TEMPP VALUES(AAA,'IN WHILE'); AAA:=AAA+1; END LOOP; <<MYPROC>> INSERT INTO TEMPP VALUES(5,'IN MYPROC');END;19) DECLARE AAA NUMBER;BEGIN FOR I IN 1..&AAA LOOP INSERT INTO TEMPP VALUES(I,'IN MAIN BLOCK'); END LOOP;END;/20) DECLARE BBB NUMBER;BEGIN

Page 39

Page 40: Oracle Questions

Oracle_Questions FOR I IN 1..&BBB LOOP INSERT INTO TEMPP VALUES(I,'IN SUBBLOCK'); END LOOP;END;/------------------------------------------------------------------------------------------------------21) DECLARE CURSOR C1 IS SELECT ENAME,SAL FROM EMP; NAME EMP.ENAME%TYPE; SALARY EMP.SAL%TYPE; BEGIN OPEN C1; FOR I IN 1..5 LOOP FETCH C1 INTO NAME,SALARY; INSERT INTO TEMP1 VALUES(NAME,SALARY); --CREATE TABLE TEMP1(A CHAR(20),B NUMBER); END LOOP; CLOSE C1;END;/------------------------------------------------------------------------------------------------------ DECLARE CURSOR C1 IS SELECT ENAME,SAL FROM EMP; NAME EMP.ENAME%TYPE; SALARY EMP.SAL%TYPE;BEGIN OPEN C1; FOR I IN 1..50 LOOP FETCH C1 INTO NAME,SALARY; INSERT INTO TEMP1 VALUES(NAME,SALARY); --CREATE TABLE TEMP1(A CHAR(20),B NUMBER);

END LOOP; CLOSE C1; END; /------------------------------------------------------------------------------------------------------ DECLARE CURSOR C1 IS SELECT ENAME,SAL FROM EMP NAME EMP.ENAME%TYPE; SALARY EMP.SAL%TYPE;

BEGIN OPEN C1; FOR I IN 1..50 LOOP FETCH C1 INTO NAME,SALARY; EXIT WHEN C1%NOTFOUND; INSERT INTO TEMP1 VALUES(NAME,SALARY); --CREATE TABLE TEMP1(A CHAR(20),B NUMBER); END LOOP; CLOSE C1;END;/------------------------------------------------------------------------------------------------------

Page 40

Page 41: Oracle Questions

Oracle_Questions DECLARE CURSOR C1 (DD NUMBER) IS SELECT ENAME,SAL FROM EMP WHERE DEPTNO=DD;

BEGIN FOR ZZZ IN C1(20) LOOP INSERT INTO TEMP1 VALUES(ZZZ.ENAME,ZZZ.SAL); --CREATE TABLE TEMP1(A CHAR(20),B NUMBER); END LOOP; END;/------------------------------------------------------------------------------------------------------ DECLARE I NUMBER:=5; J NUMBER:=12; BEGIN I:=I/J; END;/------------------------------------------------------------------------------------------------------ DECLARE I NUMBER:=5; J NUMBER:=0; BEGIN I:=I/J; EXCEPTION WHEN ZERO_DIVIDE THEN INSERT INTO TEMPP VALUES(100);END;/------------------------------------------------------------------------------------------------------ DECLARE I NUMBER:=5; J NUMBER:=1; BEGIN I:=I/J; INSERT INTO TEMPP VALUES(200); EXCEPTION WHEN ZERO_DIVIDE THEN INSERT INTO TEMPP VALUES(100); END; /------------------------------------------------------------------------------------------------------ DECLARE CURSOR C1 IS SELECT SAL FROM EMP; ZZZ NUMBER; ABCD EXCEPTION; BEGIN OPEN C1; FOR I IN 1..10 LOOP FETCH C1 INTO ZZZ; IF ZZZ > 2000 THEN RAISE ABCD; END IF; END LOOP; EXCEPTION WHEN ABCD THEN INSERT INTO TEMPP VALUES(ZZZ); END; /

DECLAREPage 41

Page 42: Oracle Questions

Oracle_QuestionsCURSOR C1 IS SELECT SAL FROM EMP; ZZZ NUMBER; ABCD EXCEPTION; BEGIN OPEN C1; FOR I IN 1..10 LOOP FETCH C1 INTO ZZZ; IF ZZZ > 2000 THEN RAISE ABCD; END IF; INSERT INTO TEMPP VALUES(ZZZ/100); END LOOP; EXCEPTION WHEN ABCD THEN INSERT INTO TEMPP VALUES(ZZZ); END;/------------------------------------------------------------------------------------------------------ DECLARE DD DATE ='15-AUG-92'; BEGIN IF DD > '01-JUN-92' THEN INSERT INTO TEMPP VALUES(100); END IF; END; /------------------------------------------------------------------------------------------------------ DECLARE LG BOOLEAN:=TRUE; BEGIN IF LG THEN INSERT INTO TEMPP VALUES(1); END IF; LG:=FALSE; IF NOT LG THEN INSERT INTO TEMPP VALUES(0); END IF; END; /DECLARELG BOOLEAN:=TRUE;BEGINIF LG THENINSERT INTO TEMPP VALUES(1,'TRUE');END IF;LG:=FALSE;IF NOT LG THENINSERT INTO TEMPP VALUES(0,'FALSE');END IF;END;/------------------------------------------------------------------------------------------------------DECLARE STR CHAR(20);

BEGIN STR:='&STR'; INSERT INTO TEMPP VALUES(10,STR);END;

Page 42

Page 43: Oracle Questions

Oracle_Questions/------------------------------------------------------------------------------------------------------ DECLARE MVAR1 CHAR(10); BEGIN MVAR1:='HELLO' || 'BYE'; INSERT INTO TEMPP VALUES(999,MVAR1); END; /DECLARE MVAR1 CHAR(10); MVAR2 CHAR(20);BEGIN MVAR1:='HELLO' || NULL || 'HI'; INSERT INTO TEMPP VALUES(999,MVAR1); MVAR2:=MVAR1 ||''|| 'COSMOS'; INSERT INTO TEMPP VALUES(999,MVAR2);END;/DECLARE AAA NUMBER:=20; BBB NUMBER:=30;BEGIN INSERT INTO TEMPP VALUES(AAA,'IN MAIN BLOCK-AAA');DECLAREBEGIN INSERT INTO TEMPP VALUES(AAA,'IN SUB-BLOCK-AAA'); INSERT INTO TEMPP VALUES(BBB,'IN SUB-BLOCK-AAA');END; INSERT INTO TEMPP VALUES(BBB,'BACK TO MAIN-BLOCK-BBB');END;/ ---------------------------------------------------DECLARE AAA NUMBER:=20;BEGIN BEGIN INSERT INTO TEMPP VALUES(AAA,'SUB-BLOCK#1'); END; BEGIN INSERT INTO TEMPP VALUES(AAA,'SUB-BLOCK#2'); END; END;BEGIN <<MAINLOOP>> FOR I IN 1..100 LOOP <<SUBLOOP>> FOR J IN 1..10 LOOP INSERT INTO TEMPP VALUES(J,'SUBLOOP'); EXIT MAINLOOP WHEN J=5; END LOOP SUBLOOP; END LOOP MAINLOOP;END;/DECLARE CURSOR C1 IS SELECT ENAME FROM EMP; CNT NUMBER(10); NAME EMP.ENAME%TYPE;BEGIN OPEN C1; LOOP FETCH C1 INTO NAME; IF C1%FOUND THEN CNT:=C1%ROWCOUNT; INSERT INTO TEMPP VALUES(CNT,NAME);

Page 43

Page 44: Oracle Questions

Oracle_Questions ELSE EXIT; END IF; END LOOP; CLOSE C1;END;/DECLARE CURSOR C1 IS SELECT EMPNO,ENAME FROM EMP; MEMPNO EMP.EMPNO%TYPE; MENAME EMP.ENAME%TYPE;BEGIN LOOP IF C1%ISOPEN THEN

FETCH C1 INTO MEMPNO,MENAME; IF C1%NOTFOUND THEN EXIT; END IF; INSERT INTO TEMPP VALUES(MEMPNO,MENAME); ELSE OPEN C1; END IF; END LOOP; CLOSE C1; END; /

DECLARE CURSOR C1(X NUMBER,Y CHAR) IS SELECT ENAME,SAL FROM EMP WHERE SAL>=X AND JOB=Y; A NUMBER; B CHAR(20);BEGIN A:=&A; B:='&B'; FOR ZZZ IN C1(A,B) LOOP INSERT INTO TEMPP VALUES(ZZZ.SAL,ZZZ.ENAME); END LOOP;END;/DECLARE NAME1 EMP.ENAME%TYPE; NAME2 EMP.ENAME%TYPE; NAME3 EMP.ENAME%TYPE; CURSOR C1 IS SELECT ENAME FROM EMP;BEGIN OPEN C1; FETCH C1 INTO NAME1; FETCH C1 INTO NAME2; FETCH C1 INTO NAME3; INSERT INTO TEMPP VALUES(1,NAME1); INSERT INTO TEMPP VALUES(2,NAME2); INSERT INTO TEMPP VALUES(3,NAME3); CLOSE C1;END;/DECLARE TSAL NUMBER(10); MULT NUMBER(10):=2; CURSOR C1 IS SELECT SAL*MULT FROM EMP;BEGIN OPEN C1; LOOP FETCH C1 INTO TSAL;

Page 44

Page 45: Oracle Questions

Oracle_Questions EXIT WHEN C1%NOTFOUND; INSERT INTO TEMPP VALUES(TSAL,'MULTIPLIED'); MULT:=5; END LOOP; CLOSE C1;END;/

DECLARE TSAL NUMBER(10); MULT NUMBER(10):=2; CURSOR C1 IS SELECT SAL*MULT FROM EMP;BEGIN OPEN C1; LOOP FETCH C1 INTO TSAL; EXIT WHEN C1%NOTFOUND; INSERT INTO TEMPP VALUES(TSAL,'MULTIPLIED'); END LOOP;

CLOSE C1; MULT:=&AAA; OPEN C1; LOOP FETCH C1 INTO TSAL; EXIT WHEN C1%NOTFOUND;

INSERT INTO TEMPP VALUES(TSAL,'MULTIPLIED AGAIN'); END LOOP; CLOSE C1;END;/DECLARE CURSOR C1 IS SELECT EMPNO,ENAME FROM EMP WHERE ENAME LIKE'S%'; MEMPNO EMP.EMPNO%TYPE; MENAME EMP.ENAME%TYPE;BEGIN OPEN C1; LOOP FETCH C1 INTO MEMPNO,MENAME; IF C1%NOTFOUND THEN EXIT; END IF; IF MENAME='JOHN' OR MEMPNO=7788 THEN INSERT INTO TEMPP VALUES(MEMPNO,MENAME); END IF; IF MENAME='SMITH' AND MEMPNO=7369 THEN INSERT INTO TEMPP VALUES(MEMPNO,MENAME); END IF; END LOOP;END;/DECLARE CURSOR C1 IS SELECT EMPNO,COMM FROM EMP; MEMPNO EMP.EMPNO%TYPE; MCOMM EMP.COMM%TYPE;BEGIN OPEN C1; LOOP FETCH C1 INTO MEMPNO,MCOMM; IF C1%NOTFOUND THEN EXIT;

Page 45

Page 46: Oracle Questions

Oracle_Questions END IF; IF MCOMM IS NULL THEN INSERT INTO TEMPP VALUES(MEMPNO,'NO COMMISSION'); END IF; END LOOP;END;/

DECLARE MNO ORD.CUSTID%TYPE; MNUM CUSTOMER.CUSTID%TYPE; MNAME CUSTOMER.NAME%TYPE; CURSOR DET IS SELECT DISTINCT CUSTID FROM ORD ORDER BY CUSTID; CURSOR MAST IS SELECT CUSTID,NAME FROM CUSTOMER;BEGIN OPEN DET; LOOP FETCH DET INTO MNO; EXIT WHEN DET%NOTFOUND; OPEN MAST; LOOP FETCH MAST INTO MNUM,MNAME; EXIT WHEN MAST%NOTFOUND; IF MNUM=MNO THEN INSERT INTO TEMPP VALUES(MNO,MNAME);

COMMIT; END IF; END LOOP; CLOSE MAST; END LOOP; CLOSE DET;END;/BEGIN DELETE FROM EMP WHERE ENAME='TOMBELL'; IF SQL%NOTFOUND THEN INSERT INTO TEMPP VALUES(100,'NO RECORDS FOUND'); END IF;END;/BEGIN UPDATE EMP SET SAL=SAL*1.5 WHERE DEPTNO=20; IF SQL%ROWCOUNT > 2 THEN INSERT INTO TEMPP VALUES(999,'2 RECORDS UPDATED'); END IF;END;/DECLARE CURSOR C1 IS SELECT * FROM EMP;BEGIN FOR ZZZ IN C1 LOOP UPDATE EMP SET COMM=ZZZ.SAL/10; END LOOP;

Page 46

Page 47: Oracle Questions

Oracle_QuestionsEND;/ -----------------------------------------------------------------------------------

DECLARE CURSOR C1 IS SELECT * FROM EMP FOR UPDATE OF COMM;BEGIN FOR ZZZ IN C1 LOOP UPDATE EMP SET COMM=ZZZ.SAL/10 WHERE CURRENT OF C1; END LOOP; END;DECLARE I NUMBER:=5; J NUMBER:=0; ERRN NUMBER; ERRMSG CHAR(200);BEGIN ERRN:=SQLCODE; ERRMSG:=SQLERRM; INSERT INTO TEMPP VALUES(ERRN,ERRMSG);END;

DECLARE MVARL CHAR(10);BEGIN MVARL:='HELLO'||'WORLD'; INSERT INTO TEMPP VALUES(999,MVARL); EXCEPTION WHEN VALUE_ERROR THEN INSERT INTO TEMPP VALUES(999,'TRUNCATION');END;/DECLARE MSAL NUMBER(15);BEGIN SELECT SAL INTO MSAL FROM EMP WHERE EMPNO=1000; EXCEPTION WHEN ZERO_DIVIDE THEN INSERT INTO TEMPP VALUES(1476,'ZERO_DIVIDE ERROR'); WHEN NO_DATA_FOUND THEN INSERT INTO TEMPP VALUES(100,'NOT FOUND ERROR');END;/DECLARE CURSOR C1 IS SELECT SAL FROM EMP; ZZZ NUMBER; ABCD EXCEPTION;BEGIN OPEN C1; FOR I IN 1..10 LOOP FETCH C1 INTO ZZZ; IF ZZZ > 2000 THEN RAISE ABCD; END IF; END LOOP; EXCEPTION WHEN ABCD THEN INSERT INTO TEMPP VALUES(ZZZ,'ABCD');END;/

DECLAREPage 47

Page 48: Oracle Questions

Oracle_Questions AAA NUMBER(10); ZZZ EXCEPTION;BEGIN DECLARE ZZZ EXCEPTION; BBB NUMBER(10);BEGIN IF &BBB < 20 THEN RAISE ZZZ; END IF; EXCEPTION WHEN ZZZ THEN INSERT INTO TEMPP VALUES(2,'IN SUB-BLOCK');END; IF &AAA=30 THEN RAISE ZZZ; END IF; EXCEPTION WHEN ZZZ THEN INSERT INTO TEMPP VALUES(1,'MAIN-BLOCK');END;/

DECLARE AAA NUMBER(10); ZZZ EXCEPTION;BEGIN DECLARE BBB NUMBER(10);BEGIN IF &BBB < 20 THEN RAISE ZZZ; END IF;END; IF &AAA=30 THENRAISE ZZZ; END IF; EXCEPTION WHEN ZZZ THEN INSERT INTO TEMPP VALUES(1,'IN MAIN_BLOCK');END;/DECLARE MENAME CHAR(20); AAA NUMBER(10):=100; BBB NUMBER; CCC NUMBER(5);BEGIN AAA:=AAA/&BBB; CCC:=999999*199; SELECT ENAME INTO MENAME FROM EMP WHERE SAL >=5000; EXCEPTION WHEN ZERO_DIVIDE THEN INSERT INTO TEMPP VALUES(999,'ERROR IN DIVISION'); WHEN TOO_MANY_ROWS THEN INSERT INTO TEMPP VALUES(-1427,'TOO MANY ROWS IS SELECT'); WHEN OTHERS THEN INSERT INTO TEMPP VALUES(2929,'OTHER EXCEPTION');END;/

Page 48

Page 49: Oracle Questions

Oracle_QuestionsDECLARE MYPROC EXCEPTION; PRAGMA EXCEPTION_INIT(MYPROC,-01843); MENAME CHAR(20);BEGIN SELECT ENAME INTO MENAME FROM EMP WHERE HIREDATE='12-DDD-88'; EXCEPTION WHEN MYPROC THEN INSERT INTO TEMPP VALUES(01843,'INVALID MONTH');END;/-------------------------------------------------------------------------------------------------------

SUBPROGRAMS AND PACKAGES

SUBPROGRAMS ARE NAMED PL/SQL BLOCKS THAT CAN ACCEPT PARAMETERS AND CAN BE INVOKED WHENEVER REQUIRED.SIMILAR TO PL/SQL BLOCKS SUBPROGRAMS ARE MADE OF* DECLARATION PART* EXECUTABLE PART* EXCEPTION HANDLING PART

SUBPROGRAMS ARE OF 2 TYPE

1)PROCEDURES2)FUNCTIONS

A PROCEDURE IS A SUBPROGRAM THAT PERFORMS A SPECIFIC ACTION IT DOES NOTRETURNS ANY VALUE FOR THE HOST ENVIRONMENT.

SYNTAX TO CREATE PROCEDURE:

CREATE OR REPLACE PROCEDURE <PROCEDURE NAME>(PARAMETER LIST) IS < DECLARATION SECTION WITH OUT DECLARE STATEMENT >;BEGIN<EXECUTION STATEMENTS><EXCEPTION HANDLERS>END;

SYNTAX TO EXECUTE A PROCEDURE:

SQL>EXEC <PROCEDURE NAME>(PARAMETER);

1) TO UPDATE THE SAL OF AN EMPLOYEE BY PASSING EMPNO AS A PARAMETER.

CREATE OR REPLACE PROCEDURE P1(ENO NUMBER) IS BEGINUPDATE EMP SET SAL=2000 WHERE EMPNO=ENO; END ;HOW TO RUN:

SQL>@<FILE NAME> / PROCEDURE CREATED

SQL>EXEC P1(7788);Page 49

Page 50: Oracle Questions

Oracle_Questions PL/SQL PROCEDURE SUCCESSFULLY COMPLETED

IF ANY ERROR HAS OCCURRED DURING EXECUTION, THE ERROR CAN BE VIEWED USING SELECT STATEMENT.

SELECT * FROM USER_ERRORS;

2) CREATE OR REPLACE PROCEDURE P2(ENO CHAR) IS BEGINUPDATE EMP SET SAL=2000 WHERE ENAME=ENO;END ;

SQL>EXEC P1('MILLER');

3) CREATE OR REPLACE PROCEDURE P3(ENO NUMBER,NAME CHAR,SAL NUMBER,DEPTNO NUMBER) IS BEGININSERT INTO EMP(EMPNO,ENAME,SAL,DEPTNO) VALUES(ENO,NAME,SAL,DEPTNO);END ;

4) CREATE OR REPLACE PROCEDURE P4(A NUMBER,B NUMBER) IS C NUMBER;D NUMBER;E NUMBER;F NUMBER;BEGINC:=A+B;D:=A*B;E:=A-B;F:=A/B;DBMS_OUTPUT.PUT_LINE('ADDED RESULT='||C);DBMS_OUTPUT.PUT_LINE('MULTIPLIED RESULT='||D);DBMS_OUTPUT.PUT_LINE('SUBTRACTED RESULT='||E);DBMS_OUTPUT.PUT_LINE('DIVIDED RESULT='||F);END;

5)OUT PARAMETER:CREATE OR REPLACE PROCEDURE P1(A IN NUMBER,B OUT NUMBER) IS C NUMBER;BEGINSELECT SAL INTO C FROM EMP WHERE EMPNO=A; IF C > 1000 THEN B:=2000; END IF;END;

THE PROCEDURE P1 IS EXECUTED BY THE FOLLOWING BLOCK

DECLARE A NUMBER; B NUMBER; BEGIN P1(7788,B); DBMS_OUTPUT.PUT_LINE('THE VALUE OF B ='||B); END; /THE VALUE OF B IS B=2000

6)IN OUT PARAMETER:CREATE OR REPLACE PROCEDURE P2(A IN NUMBER,B IN OUT NUMBER) ISC NUMBER;BEGIN

Page 50

Page 51: Oracle Questions

Oracle_QuestionsSELECT SAL,DEPTNO INTO C,B FROM EMP WHERE EMPNO=A; IF B > 10 THEN B:=20; END IF;END;

THE PROCEDURE P1 IS EXECUTED BY THE FOLLOWING BLOCK DECLARE A NUMBER; B NUMBER; BEGIN P2(7876,B); DBMS_OUTPUT.PUT_LINE('THE VALUE OF B ='||B); END; / THE VALUE OF B =20

DELETE PROCEDURE <PROCEDURE NAME>;

FUNCTIONS:A FUNCTION IS A SUBPROGRAM THAT CAN PERFORMS AN ACTION AND RETURNSA VALUE TO HOST ENVIRONMENT.

SYNTAX:

CREATE OR REPLACE FUNCTION <FUNCTION NAME> (PARAMETER LIST)RETURN DATATYPE IS < DECLARATION SECTION WITH OUT DECLARE STATEMENT >;BEGIN<EXECUTION STATEMENTS><EXCEPTION HANDLERS>RETURN VARIABLE;END;1) CREATE OR REPLACE FUNCTION F1(A NUMBER,B CHAR,C NUMBER) RETURN NUMBER ISD NUMBER;BEGINIF B='+' THEN D:=A+C;ELSIF B='-' THEN D:=A-C;ELSIF B='*' THEN D:=A*C;ELSIF B='/' THEN D:=A/C;END IF;RETURN (D);END;

THE FUNCTION F1 IS EXECUTED BY THE FOLLOWING BLOCK

DECLAREA NUMBER:=&A;B CHAR:='&B';C NUMBER:=&C;D NUMBER;BEGIND:=F1(A,B,C);DBMS_OUTPUT.PUT_LINE('THE VALUE OF D='||D);END;

2) CREATE OR REPLACE FUNCTION F2 RETURN NUMBER ISENO NUMBER;BEGIN

Page 51

Page 52: Oracle Questions

Oracle_QuestionsSELECT MAX(EMPNO)+1 INTO ENO FROM EMP;RETURN ENO;END;FUNCTION F2 IS EXECUTED BY FOLLOWING PROCEDURE.CREATE OR REPLACE PROCEDURE PF2 (NAME CHAR,JOB CHAR,SAL NUMBER) ISENO NUMBER;BEGINENO:=F2;INSERT INTO EMP(EMPNO,ENAME,JOB,SAL,DEPTNO)VALUES(ENO,NAME,JOB,SAL,10);END;

3) CREATE OR REPLACE FUNCTION G1(N NUMBER) RETURN CHAR ISE VARCHAR2(6):='EVEN';O VARCHAR2(6):='ODD';K NUMBER;BEGINK:=MOD(N,2);IF K=0 THENRETURN E;ELSE RETURN O;END IF;END;

HOW TO RUN:

SQL> SELECT G1(22) FROM DUAL;PACKAGE:A PACKAGE IS AN ENCAPSULATION OF RELATED SUBPROGRAMS,CURSORS,EXCEPTION VARIABLES AND CONSTANTS.PACKAGES CANNOT BE CALLED ,HENCE WE CANNOT PASS PARAMETERS AS WE DO IN SUBPROGRAMS.PACKAGE CAN BE CREATED USING* CREATE PACKAGE COMMAND* CREATE PACKAGE BODY COMMAND

SYNTAX TO CREATE PACKAGE:CREATE OR REPLACE PACKAGE<PACKAGE NAME> ISPROCEDURE <PROCEDURE NAME> (PARAMETER LIST);PROCEDURE <PROCEDURE NAME> (PARAMETER LIST);....FUNCTION <FUNCTION NAME> <PARAMETER LIST> RETURN DATATYPE;..END <PACKAGE NAME>; SYNTAX TO CREATE PACKAGE BODY:CREATE OR REPLACE PACKAGE BODY <PACKAGE NAME> AS PROCEDURE <PROCEDURE NAME> (PARAMETER LIST) IS < DECLARATION SECTION WITH OUT DECLARE STATEMENT >; BEGIN <EXECUTION STATEMENTS> <EXCEPTION HANDLERS> END; PROCEDURE <PROCEDURE NAME>..... ..... ..... END; FUNCTION <FUNCTION NAME>(PARAMETER LIST) RETURN DATATYPE IS < DECLARATION SECTION WITH OUT DECLARE STATEMENT >; BEGIN <EXECUTION STATEMENTS> <EXCEPTION HANDLERS>

Page 52

Page 53: Oracle Questions

Oracle_Questions RETURN VARIABLE; END; .... .... .....END <PACKAGE NAME>;

1) CREATE OR REPLACE PACKAGE PK1 ISPROCEDURE PP1 (EMPNO NUMBER,SAL NUMBER,DEPTNO NUMBER);FUNCTION PF1(A NUMBER,B CHAR,C NUMBER) RETURN NUMBER ;END;

CREATE OR REPLACE PACKAGE BODY PK1 AS PROCEDURE PP1(EMPNO NUMBER,SAL NUMBER,DEPTNO NUMBER) IS BEGIN INSERT INTO EMP(EMPNO,SAL,DEPTNO)VALUES(EMPNO,SAL,DEPTNO); END;

FUNCTION PF1(A NUMBER,B CHAR,C NUMBER) RETURN NUMBER IS D NUMBER; BEGIN IF B='+' THEN D:=A+C; ELSIF B='-' THEN D:=A-C; ELSIF B='*' THEN D:=A*C; ELSIF B='/' THEN D:=A/C; END IF; RETURN (D); END;END PK1;HOW TO EXECUTE THE PROCEDURE PP1 IN PACKAGE PK1:SQL> EXEC PK1.PP1(9999,7000,20);HOW TO EXECUTE THE FUNCTION PF1 IN PACKAGE PK1:DECLAREA NUMBER:=&A;B CHAR:='&B';C NUMBER:=&C;D NUMBER;

BEGIND:=PK1.PF1(A,B,C);DBMS_OUTPUT.PUT_LINE('THE VALUE OF D='||D);END;

TRIGGERSDATA BASE TRIGGER CAN BE USED FOR FOLLOWING PURPOSESA)TO MAINTAIN SECURITYB)TO REPLICATE DATA AUTOMATICALLYC)TO ENFORCE INTEGRITY CONSTRAINTSD)DATA MODIFICATION,etcIF WE DELETE ROWS IN EMP9 TABLE WE SHOULD GET THE MESSAGE

Page 53

Page 54: Oracle Questions

Oracle_Questions 1)ROW LEVEL:CREATE OR REPLACE TRIGGER T1 BEFORE DELETE ON EMP9 FOR EACH ROWBEGINDBMS_OUTPUT.PUT_LINE('DELETED');END;OUTPUT:SQL>SET SERVEROUTPUT ONSQL>DELETE FROM EMP9 WHERE DEPTNO=30; 'DELETED' 'DELETED' 'DELETED' 3 ROWS DELETED

2)STATEMENT LEVEL:CREATE OR REPLACE TRIGGER T2 BEFORE DELETE ON EMP9 BEGINDBMS_OUTPUT.PUT_LINE('DELETED');END;

OUTPUT:

SQL>DELETE FROM EMP9 WHERE DEPTNO=30; 'DELETED' 3 ROWS DELETED

3)IF THE USER IS INSERTING/UPDATING A ROW WITH SAL>3000 FOR JOBS OTHER THAN MANAGERS THEN RAISE AN ERROR. ==============================================CREATE OR REPLACE TRIGGER T3 BEFORE INSERT OR UPDATE ON EMPFOR EACH ROWBEGIN

IF :NEW.SAL>3000 AND :NEW.JOB<>'MANAGER' THEN RAISE_APPLICATION_ERROR(-20004,'NOT POSSIBLE'); END IF;END;4)TO AUTOMATICALLY INSERT A SEQUENCE INTO A COLUMN(REGNO). FIRST CREATE A TABLE CLASS WITH 2 COLIMNS ie,NAME ,REGNO =====================================================CREATE OR REPLACE TRIGGER T4 BEFORE INSERT OR UPDATE OR DELETE ON CLASSFOR EACH ROWBEGIN SELECT S1.NEXTVAL INTO :NEW.REGNO FROM DUAL;END;

5) TO AUTOMATICALLY INSERT VALUES INTO TABLE EMP6 WHEN WE INSERT NEW ROWS INTO EMP TABLE. FIRST CREATE A TABLE EMP6 WITH 4 COLIMNS ie,NAME,EMPNO,SALARY,DEPTNO.=========================================================CREATE OR REPLACE TRIGGER T5 BEFORE INSERT ON EMPFOR EACH ROWBEGININSERT INTO EMP6 VALUES(:NEW.ENAME,:NEW.EMPNO,:NEW.SAL,:NEW.DEPTNO);

Page 54

Page 55: Oracle Questions

Oracle_QuestionsEND;

6) FIRST CREATE TABLES EMP8 AND DEPT8 WITH NO REFERENTIAL INTEGRITY CONSTRAINT BETWEEN THEM.

NOW IF WE TRY TO INSERT A ROW IN EMP8 TABLE WITH DEPTNO VALUE OTHER THAN THE DEPTNO VALUE OF DEPT8 TABLE IT SHOULD SHOW AN ERROR. =========================================================

CREATE OR REPLACE TRIGGER T6 BEFORE INSERT OR UPDATE ON EMP8FOR EACH ROWDECLAREA NUMBER;BEGINSELECT DEPTNO INTO A FROM DEPT8 WHERE DEPTNO=:NEW.DEPTNO;EXCEPTIONWHEN NO_DATA_FOUND THENRAISE_APPLICATION_ERROR(-20004,'PARENT KEY NOT FOUND');END;

7) IF WE TRY DELETING A ROW FROM DEPT8 TABLE WHOSE DEPTNO DETAILS ARE PRESENT IN EMP8 TABLE. =========================================================CREATE OR REPLACE TRIGGER TR69 BEFORE DELETE ON DEPT8 FOR EACH ROW DECLARE CURSOR C1 IS SELECT DEPTNO FROM EMP9 WHERE DEPTNO=:OLD.DEPTNO; A NUMBER; BEGIN OPEN C1; FETCH C1 INTO A; IF C1%FOUND THEN RAISE_APPLICATION_ERROR(-20111,'CHILD RECORDS FOUND'); END IF; CLOSE C1;EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE('DELETING RECORDS...');END;

8)ON DELETE CASCADE ie,IF WE DELETE A ROW IN DEPT8 TABLE WHOSE DEPTNO DETAILS ARE PRESENT IN EMP8 TABLE,IT SHOULD AS WELL DELETE ALL THE ROWS IN EMP8 TABLE WHOSE DEPTNO MATCHES WITH DELETED DEPTNO FROM DEPT9 TABLE.=========================================================

CREATE OR REPLACE TRIGGER TR69 BEFORE DELETE ON DEPT8 FOR EACH ROW DECLARE CURSOR C1 IS SELECT DEPTNO FROM EMP9 WHERE DEPTNO=:OLD.DEPTNO; A NUMBER; BEGIN

OPEN C1; FETCH C1 INTO A; IF C1%FOUND THEN RAISE_APPLICATION_ERROR(-20111,'CHILD RECORDS FOUND'); END IF; CLOSE C1;EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE('DELETING RECORDS...');END;

9) FOR NO TRANSACTION ON 13 AND 29CREATE OR REPLACE TRIGGER T10 BEFORE INSERT OR UPDATE OR DELETE ON EMP8FOR EACH ROWBEGIN

Page 55

Page 56: Oracle Questions

Oracle_QuestionsIF TO_CHAR(SYSDATE,'DD') IN (13,29) THENRAISE_APPLICATION_ERROR(-20009,'NO TRANSACTION TODAY ');END IF;END;10) TO GET DIFFERENT MESSAGESCREATE OR REPLACE TRIGGER T11 BEFORE INSERT OR UPDATE OR DELETE ON EMP9FOR EACH ROW

BEGINIF INSERTING THENDBMS_OUTPUT.PUT_LINE('INSERTING RECORD');END IF;IF DELETING THENDBMS_OUTPUT.PUT_LINE('DELETING RECORD');END IF;IF UPDATING THENDBMS_OUTPUT.PUT_LINE('UPDATING RECORD');END IF;END;

SQL>ALTER TRIGGER <TRIGGER NAME> DISABLE;SQL>ALTER TRIGGER <TRIGGER NAME> ENABLE;SQL>ALTER TABLE <TABLE NAME> DISABLE ALL TRIGGERS;SQL>ALTER TABLE <TABLE NAME> ENABLE ALL TRIGGERS;SQL>DROP TRIGGER <TRIGGER NAME>;

This section deals with sql* loader version 7.0 and basics of exp and impSQL*Loader Basics

SQL*Loader moves data from external files into tables in an Oracle database. It has many features of the DB2 Load Utility from IBM. It also has several other features that add power and flexibility.

SQL*Loader loads data in a variety of formats, performs filtering (selectively loading recordsbased upon the data values), and loads multiple tables simultaneously.

During execution, SQL*Loader produces a detailed log file with statistics about the load. It may also produce a bad file (containing records rejected because of incorrect data) and a discard file (containing records that did not meet the specified selection criteria).

Direct Path Load vs. Conventional Path Load Method

Direct path loads can be significantly faster than conventional path loads.Direct path loads achieve this performance gain by eliminating much of the Oracle databaseoverhead by writing directly to the database files. Conventional Path Loads

Page 56

Page 57: Oracle Questions

Oracle_Questions

Conventional path loads (the default) use the SQL command INSERT and a bind array buffer to loaddata into database tables. This method is used by all Oracle tools and applications.When SQL*Loader performs a conventional path load, it competes equally with all other processes for buffer resources. This can slow the load significantly. Extra overheadis added as SQL commands are generated, passed to Oracle, and processed.

The Concept of Mapping DataSQL*Loader must be told where and in what format the data to be loaded is and how tomap thedata to Oracle format. Definitions in the control file will include: ospecifications for loading logical records into tables ofield condition specifications ocolumn and field specifications odata field position specifications odatatype specifications obind array size specifications ospecifications for setting columns to null or zero ospecifications for loading all-blank fields ospecifications for trimming blanks and tabs ospecifications to preserve whitespace ospecifications for applying SQL operators to fields

CASE1.CTL:

LOAD DATA INFILE * INTO TABLE dept FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' (deptno, dname, loc) BEGINDATA12,RESEARCH,"SARATOGA" 10,"ACCOUNTING",CLEVELAND 11,"ART",SALEM 13,FINANCE,"BOSTON" 21,"SALES",PHILA. 22,"SALES",ROCHESTER 42,"INT'L","SAN FRAN"

Invoking SQL*LoaderTo run this example, invoke SQL*Loader with the command:

SQLLDR CONTROL=foo.ctl, LOG=bar.log, BAD=baz.bad, DATA=etc.dat USERID=scott/tiger, ERRORS=999, LOAD=2000, DISCARD=toss.dis, DISCARDMAX=5

CASE2.CTL. LOAD DATA INFILE 'ulcase2.dat' INTO TABLE emp (empno POSITION(01:04) INTEGER EXTERNAL,

Page 57

Page 58: Oracle Questions

Oracle_Questions ename POSITION(06:15) CHAR, job POSITION(17:25) CHAR, mgr POSITION(27:30) INTEGER EXTERNAL, sal POSITION(32:39) DECIMAL EXTERNAL, comm POSITION(41:48) DECIMAL EXTERNAL, deptno POSITION(50:51) INTEGER EXTERNAL)

CASE2.DAT. Blank fields are set to null automatically.7782 CLARK MANAGER 7839 2572.50 107839 KING PRESIDENT 5500.00 107934 MILLER CLERK 7782 920.00 107566 JONES MANAGER 7839 3123.75 207499 ALLEN SALESMAN 7698 1600.00 300.00 30

7654 MARTIN SALESMAN 7698 1312.50 1400.00 30

Loading a Delimited, Free-Format FileLOAD DATAINFILE *APPENDINTO TABLE emp FIELDS TERMINATED BY "," OPTIONALLY ENCLOSED BY '"' (empno, ename, job, mgr, hiredate DATE(20) "DD-Month-YYYY", sal, comm, deptno CHAR TERMINATED BY ':', projno, loadseq SEQUENCE(MAX,1)) BEGINDATA 7782, "Clark", "Manager", 7839, 09-June-1981, 2572.50,, 10:101 7839, "King", "President", , 17-November-1981,5500.00,,10:1027934, "Miller", "Clerk", 7782, 23-January-1982, 920.00,, 10:102 7566, "Jones", "Manager", 7839, 02-April-1981, 3123.75,, 20:101 7499, "Allen", "Salesman", 7698, 20-February-1981, 1600.00,300.00, 30:103 7654, "Martin", "Salesman", 7698, 28-September-1981, 1312.50,1400.00, 3:1037658, "Chan", "Analyst", 7566, 03-May-1982, 3450,, 20:101

Loading Combined Physical RecordsCASE4.CTL: LOAD DATA INFILE 'case4.dat' DISCARDFILE 'case4.dsc' DISCARDMAX 999 REPLACE CONTINUEIF THIS (1) = '*'INTO TABLE emp (empno POSITION(1:4) INTEGER EXTERNAL, ename POSITION(6:15) CHAR, job POSITION(17:25) CHAR,mgr POSITION(27:30) INTEGER EXTERNAL, sal POSITION(32:39) DECIMAL EXTERNAL, comm POSITION(41:48) DECIMAL EXTERNAL, deptno POSITION(50:51) INTEGER EXTERNAL, hiredate POSITION(52:60) INTEGER EXTERNAL)The Data File*7782 CLARK MANAGER 7839 2572.50 -10 2512-NOV-85*7839 KING PRESIDENT 5500.00 2505-APR-83*7934 MILLER CLERK 7782 920.00 2508-MAY-80

*7566 JONES MANAGER 7839 3123.75 2517-JUL-85Page 58

Page 59: Oracle Questions

Oracle_Questions

Case 5: Loading Data into Multiple Tables

LOAD DATA INFILE 'ulcase5.dat' BADFILE 'ulcase5.bad' DISCARDFILE 'ulcase5.dsc'REPLACEINTO TABLE emp (empno POSITION(1:4) INTEGER EXTERNAL, ename POSITION(6:15) CHAR, deptno POSITION(17:18) CHAR, mgr POSITION(20:23) INTEGER EXTERNAL) INTO TABLE proj WHEN projno != ' ' (empno POSITION(1:4) INTEGER EXTERNAL, projno POSITION(25:27) INTEGER EXTERNAL) -- 1st proj INTO TABLE proj WHEN projno != ' '(empno POSITION(1:4) INTEGER EXTERNAL, projno POSITION(29:31 INTEGER EXTERNAL) -- 2nd proj INTO TABLE projWHEN projno != ' ' (empno POSITION(1:4) INTEGER EXTERNAL, projno POSITION(33:35) INTEGER EXTERNAL) -- 3rd proj

1234 BAKER 10 9999 101 102 1031234 JOKER 10 9999 777 888 9992664 YOUNG 20 2893 425 abc 1025321 OTOOLE 10 9999 321 55 402134 FARMER 20 4555 236 4562414 LITTLE 20 5634 236 456 406542 LEE 10 4532 102 321 142849 EDDS xx 4555 294 40

--This section deals with some topics from DBA which are useful for Interview purpose.

Database StructureAn Oracle database has both a physical and a logical structure.

Physical Database Structure Each Oracle database is made of three types of files: one or more datafiles, two ormore redo log files, and one or more control files.

Logical Database StructureAn Oracle database's logical structure is determined by· One or more tablespaces.· The database's schema objectsThe logical storage structures, including tablespaces, segments, and extents, dictate how the physical space of a database is used

Page 59

Page 60: Oracle Questions

Oracle_QuestionsEach database is logically divided into one or more tablespaces.Online and Offline Tablespaces A tablespace can be online (accessible) or offline (not accessible) Oracle Data BlocksThe next level of logical database space is called an extent. An extent is a specific number of contiguous data blocks, obtained in a single allocation, used to store a specific type of information.

SEGMENTS The level of logical database storage above an extent is called a segment.Data SegmentIndex SegmentRollback SegmentTemporary Segment

PHYSICAL DATABASE STRUCTURESDatafilesEvery Oracle database has one or more physical datafiles. A database's datafiles contain all the database data.Redo Log Files

Every Oracle database has a set of two or more redo log files. The set of redo log files for a database is collectively known as the database's redo log. The primary function of the redo log is to record all changes made to dataControl Files

Every Oracle database has a control file. A control file contains entries that specify the physical structure of the database

THE DATA DICTIONARYSystem Global Area (SGA)

The System Global Area (SGA) is a shared memory region that contains data and control information for one Oracle instance. Oracle allocates the system global areawhen an instance starts and deallocates it when the instance shuts down. Each instance has its own system global area.The information stored within the system global area is divided into several types of memory structures, including the database buffers, redo log buffer, and the shared pool. These areas have fixed sizes Database Buffer Cache Database buffers of the system global area store the most recently used blocks of database data;Redo Log Buffer The redo log buffer of the system global area stores redo entries --a log of changes made to the database. Shared Pool The shared pool is a portion of the system global area that contains shared memory constructs such as shared SQL areasThe Program Global Area (PGA) is a memory buffer that contains data and control information for a server process A user process is created and maintained to execute the software code of an application program (such as a Pro*C/C++ program) or an Oracle tool (such as Server Manager)Server Processes Oracle creates server processes to handle requests from connected user processes.Background Processes Oracle creates a set of background processes for Each instance An SGA and the Oracle background processes constitute an Oracle Database Writer (DBWR) The Database Writer writes modified blocks from the database buffer cache to the datafiles.In general, DBWR writes only when more data needs to be read into the system global area and too few database buffers are free. The least recently used data is written to the datafiles first.

Checkpoint (CKPT) At specific times, all modified database buffers in the system global area are written to the datafiles by DBWR. The Checkpoint process is responsible for signalling DBWR at checkpoints and updating all the datafiles and control files of the database to indicate the most recent checkpoint. CKPT is

Page 60

Page 61: Oracle Questions

Oracle_Questionsoptional;

System Monitor (SMON) The system monitor performs instance recovery at instance startup. SMON also cleans up temporary segments that are no longer in use and recovers dead transactions skipped during crash and instance recovery because of file-read or offline errors

Process Monitor (PMON) The process monitor performs process recovery when a user process fails

.Archiver (ARCH) The archiver copies the online redo log files to archival storage when they are full. ARCH is active only when a database's redo log is used in ARCHIVELOG mode

Recoverer (RECO) The recoverer is used to resolve distributed transactions that are pending due to a network or system failure in a distributed database

Dispatcher (Dnnn) Dispatchers are optional background processes, present only when amulti-threaded server configuration is used.

Lock (LCKn) Up to ten lock processes (LCK0, . . ., LCK9) are used for inter-instance locking when the Oracle Parallel Server is used;

DATABASE ADMINISTRATORA database administrator's responsibilities can include the following tasks:oinstalling and upgrading the Oracle7 Server and application toolsoallocating system storage and planning future storage requirements for the databasesystemocreating primary database storage structures (tablespaces) after application developers have designed an applicationocreating primary objects (tables, views, indexes) once application developers have designed an applicationomodifying the database structure, as necessary, from information given by application developersoenrolling users and maintaining system securityoensuring compliance with your Oracle7 license agreementocontrolling and monitoring user access to the databaseomonitoring and optimizing the performance of the databaseoplanning for backup and recovery of database informationomaintaining archived data on tapeobacking up and restoring the databaseocontacting Oracle Corporation for technical support

Database Administrator UsernamesTwo user accounts are automatically created with the database and granted the DBA role.These two user accounts are:oSYS (initial password: CHANGE_ON_INSTALL)oSYSTEM (initial password: MANAGER)

To Configure an Oracle7 ServeroStep 1: Install the Oracle7 SoftwareoStep 2: Evaluate the Database Server HardwareoStep 3: Plan the DatabaseoStep 4: Create and Open the DatabaseoStep 5: Implement the Database DesignoStep 6: Back up the DatabaseoStep 7: Enroll System UsersoStep 8: Tune Database Performance

TABLESPACESCREATE TABLESPACE rb_segs DATAFILE 'datafilers_1' SIZE 50M

Page 61

Page 62: Oracle Questions

Oracle_Questions DEFAULT STORAGE ( INITIAL 50K NEXT 50K MINEXTENTS 2 MAXEXTENTS 50 PCTINCREASE 0)

To identify a tablespace as temporary during tablespace creation, issue the following statement:

CREATE TABLESPACE tablespace TEMPORARY

Altering Tablespace Availability

You can bring an offline tablespace online to make the schema objects within the tablespace available to database users

ALTER TABLESPACE users ONLINE; ALTER TABLESPACE flights READ ONLYALTER TABLESPACE flights READ WRITE;

DATAFILESYou can create and add datafiles to a tablespace to increase the total amount of disk space allocated for the tablespaceALTER TABLESPACE rb_segs ADD DATAFILE 'filename1' SIZE 1M;

The following example enables automatic extension for a datafile, FILENAME2, added to the USERS tablespace:ALTER TABLESPACE users ADD DATAFILE 'filename2' SIZE 10M AUTOEXTEND ON NEXT 512K MAXSIZE 250M

ALTER TABLESPACE users RENAME DATAFILE 'filename1', 'filename2' TO 'filename3', 'filename4';

Guidelines for Managing Schema ObjectsThe default for PCTFREE is 10 percent. You can use any integer between 0 and 99, inclusive, as long as the sum of PCTFREE and PCTUSED does not exceed 100.A smaller PCTFREE has the following effects:oreserves less room for updates to expand existing table rowsoallows inserts to fill the block more completelyomay save space, because the total data for a table or index is stored in fewer blocks (more rows or entries per block)A larger PCTFREE has the following effects:oreserves more room for future updates to existing table rowsomay require more blocks for the same amount of inserted data (inserting fewer rows per block)omay improve update performance, because Oracle does not need to chain row pieces asfrequently, if ever

A smaller PCTUSED has the following effects:oreduces processing costs incurred during UPDATE and DELETE statements for moving a block to the free list when it has fallen below that percentage of usageoincreases the unused space in a databaseA larger PCTUSED has the following effects:oimproves space efficiencyoincreases processing cost during INSERTs and UPDATEs`

The smaller the difference between 100 and the sum of PCTFREE and PCTUSED (as in Page 62

Page 63: Oracle Questions

Oracle_QuestionsPCTUSED of 75, PCTFREE of 20), the more efficient space usage is, at some performance cost.

Scenario1: Common activity includes UPDATE statements that increase the size of the rows.PCTFREE = 20 PCTUSED = 40

Scenario2: Most activity includes INSERT and DELETE statements, and UPDATE statements that do not increase the size of affected rows.PCTFREE = 5 PCTUSED = 60

Scenario3: The table is very large; therefore, storage is a primary concern. Most activity includes read-only transactions.PCTFREE = 5 PCTUSED = 90

Setting Storage ParametersINITIAL The size, in bytes, of the first extent allocated when a segment is created.Default: 5 data blocks Minimum: 2 data blocks (rounded up) Maximum: operating system-specific

NEXT The size, in bytes, of the next incremental extent to be allocated for a segment. The second extent is equal to the original setting for NEXT. From there forward, NEXT is set to the previous size of NEXT multiplied by (1 + PCTINCREASE/100).

MAXEXTENTS The total number of extents, including the first, that can ever be allocated for thesegment.Default: dependent on the data block size and operating system Minimum: 1 (extent) Maximum: unlimited

MINEXTENTS The total number of extents to be allocated when the segment is created. This allowsfor a large allocation of space at creation time, even if contiguous space is not available.Default: 1 (extent) Minimum: 1 (extent) Maximum: operating system-specific

PCTINCREASE The percent by which each incremental extent grows over the last incremental extent allocated for a segment. If PCTINCREASE is 0, then all incremental extents are the same size.

INITRANS Reserves a pre-allocated amount of space for an initial number of transaction entries to access rows in the data block concurrently.Default value for a table is 1.

The MAXTRANS parameter limits the number of transaction entries that can concurrently use data in a data block.

Example-CREATE TABLE test_storage ( . . . ) STORAGE (INITIAL 100K NEXT 100K MINEXTENTS 2 MAXEXTENTS 5 PCTINCREASE 50);General Management of Schema ObjectsThe CREATE SCHEMA command is used to create several tables and views and grants inone operation;

CREATE SCHEMA AUTHORIZATION scott CREATE TABLE dept (deptno NUMBER(3,0) PRIMARY KEY, dname VARCHAR2(15), loc VARCHAR2(25)

Page 63

Page 64: Oracle Questions

Oracle_Questions

CREATE TABLE emp ( empno NUMBER(5,0) PRIMARY KEY, ename VARCHAR2(15) NOT NULL, job VARCHAR2(10), mgr NUMBER(5,0), hiredate DATE DEFAULT (sysdate), sal NUMBER(7,2), comm NUMBER(7,2), deptno NUMBER(3,0) NOT NULLCONSTRAINT dept_fkey REFERENCES dept) CREATE VIEW sales_staff AS SELECT empno, ename, sal, comm FROM emp WHERE deptno = 30 WITH CHECK OPTION CONSTRAINT sales_staff_cnst GRANT SELECT ON sales_staff TO human_resources;

Analyzing TablesTable Statistics You can gather the following statistics on a table: Note: The * symbol indicates that the numbers will always be an exact value when computing statistics.onumber of rowsonumber of blocks that have been used *onumber of blocks never usedoaverage available free spaceonumber of chained rowsoaverage row lengthonumber of distinct values per columnothe second smallest value per column *othe second largest value per column *Note: Statistics for all indexes associated with a table are automatically gathered when the table is analyzed.

The following statement computes statistics for the EMP table:ANALYZE TABLE emp COMPUTE STATISTICS;

ANALYZE TABLE emp VALIDATE STRUCTURE;

ANALYZE TABLE emp VALIDATE STRUCTURE CASCADE; Disabling Enabled Constraints

The following statements disable integrity constraints:ALTER TABLE dept DISABLE CONSTRAINT dname_ukey; ALTER TABLE dept DISABLE PRIMARY KEY, DISABLE UNIQUE (dname, loc);

Establishing Security PoliciesManaging Users and ResourcesALTER USER avyrros DEFAULT ROLE DEVELOPER;ALTER USER avyrros DROP USER jones CASCADE; DEFAULT ROLE ALL EXCEPT payroll;Managing Resources with ProfileA profile is a named set of resource limits. If resource limits are turned on, Oracle limits database usage and instance resources to whatever is defined in the user's profile.

The following statement creates the profile CLERK:CREATE PROFILE clerk LIMIT

Page 64

Page 65: Oracle Questions

Oracle_Questions SESSIONS_PER_USER 2 CPU_PER_SESSION unlimited CPU_PER_CALL 6000 LOGICAL_READS_PER_SESSION unlimited LOGICAL_READS_PER_CALL 100 IDLE_TIME 30 CONNECT_TIME 480

CREATE USER jfee IDENTIFIED BY wildcat DEFAULT TABLESPACE users TEMPORARY TABLESPACE temp_ts QUOTA 500K ON users PROFILE clerk;

Identifying User PrivilegesThis section describes Oracle user privileges, and includes the following topics: oSystem PrivilegesoObject PrivilegesThere are over 80 distinct system privileges. Each system privilege allows a user toperform a particular database operation or class of database operations. Object Privileges

Each type of object has different privileges associated with it. Table 20 - 2 summarizes the object privileges available for each type of object

CREATE ROLE clerk IDENTIFIED BY bicentennial;

GRANT create session, accts_pay TO jward;GRANT insert(ename, job) ON emp TO jfee, tsmith; GRANT INSERT (acct_no) ON accounts TO scott;REVOKE create table, accts_rec FROM tsmith; REVOKE select, insert ON emp FROM jfee, tsmith;REVOKE UPDATE ON dept FROM human_resources;GRANT UPDATE (dname) ON dept TO human_resources;

AUDITING DATABASE Option SQL Statements Audited

ALTER SYSTEM ALTER SYSTEM

CLUSTER CREATE CLUSTER ALTER CLUSTER TRUNCATE CLUSTER DROP CLUSTER

DATABASE LINK CREATE DATABASE LINK DROP DATABASE LINK TABLESPACE CREATE TABLESPACE ALTER TABLESPACE DROP TABLESPACE

INDEX CREATE INDEX ALTER INDEX DROP INDEX

TABLE CREATE TABLE ALTER TABLE DROP TABLEIN ORDER TO AUDIT GIVE SQL>AUDIT SESSION WHENEVER SUCCESSFUL; SQL>NO AUDIT; SQL>AUDIT DELETE ANY TABLE BY ACCESS WHENEVER NOT SUCCESSFUL;You can set any auditing option, and specify the following conditions for auditing:oWHENEVER SUCCESSFUL/WHENEVER NOT SUCCESSFULoBY SESSION/BY ACCESS

AUDIT SESSION BY scott, lori;

AUDIT DELETE ANY TABLE; AUDIT SELECT TABLE, INSERT TABLE, DELETE TABLE, EXECUTE ANY PROCEDURE BY ACCESS WHENEVER NOT SUCCESSFUL;

Page 65

Page 66: Oracle Questions

Oracle_QuestionsNOAUDIT session;NOAUDIT session BY scott, lori;NOAUDIT DELETE ANY TABLE;NOAUDIT SELECT TABLE, INSERT TABLE, DELETE TABLE,EXECUTE ANY PROCEDURE;oSTMT_AUDIT_OPTION_MAPoAUDIT_ACTIONSoALL_DEF_AUDIT_OPTSoDBA_STMT_AUDIT_OPTSoUSER_OBJ_AUDIT_OPTS, DBA_OBJ_AUDIT_OPTSoUSER_AUDIT_TRAIL, DBA_AUDIT_TRAILoUSER_AUDIT_SESSION, DBA_AUDIT_SESSIONoUSER_AUDIT_STATEMENT, DBA_AUDIT_STATEMENToUSER_AUDIT_OBJECT, DBA_AUDIT_OBJECToDBA_AUDIT_EXISTSoUSER_AUDIT_SESSION, DBA_AUDIT_SESSIONoUSER_TAB_AUDIT_OPTS NOAUDIT ALL;SNAPSHOTS.CREATE SNAPSHOT emp_sf PCTFREE 5 PCTUSED 60 TABLESPACE users STORAGE (INITIAL 50K NEXT 50K PCTINCREASE 50) REFRESH FAST START WITH sysdate NEXT sysdate + 7 AS SELECT * FROM [email protected];

DROP SNAPSHOT emp; SELECT * FROM <SNAPSHOT NAME>;Snapshot Log CREATE SNAPSHOT LOG ON scott.emp TABLESPACE users STORAGE (INITIAL 10K NEXT 10K PCTINCREASE 50) PCTFREE 5;DROP SNAPSHOT LOG emp_log;

DBMS_REFERESH.MAKE( name => 'acctg', list => 'acct_rec, acct_pay', next_date => SYSDATE, interval => 'SYSDATE + 1/24', implicit_destroy => TRUE);

SYSDATE + 7

oUSER_REFRESHoUSER_REFRESH_CHILDREN

FOR MANUAL REFRESH. DBMS_REFRESH.REFRESH('acctg');

SYSTEM DATAROLLBACK1ROLLBACK2INDEXTEMP1TEMP2

Page 66

Page 67: Oracle Questions

Oracle_QuestionsTEMP3USERSTOOLSORACLE SWDATA_1LOG1LOG2LOG3CONTROL1CONTROL2CONTROL3ARCHIVE REDO LOG FILEPHYSICAL BACKUPLOGICAL BACKUPThis section deals with backup. BACKUP AND RECOVERYNOARCHIVELOG ModeWhen you run your database in NOARCHIVELOG mode, the archiving of the online redo log is disabled.ARCHIVELOG ModeWhen you run a database in ARCHIVELOG mode, the archiving of the online redo log is enabled.Turning Archiving On and OffSetting the Initial Database Archiving ModeNOARCHIVELOG is the default.Changing the Database Archiving Mode To switch a database's archiving mode between NOARCHIVELOG and ARCHIVELOG modeALTER DATABASE ARCHIVELOG;Before switching the database's archiving mode, perform the following operations: 1) Shut down the database instance. 2) Back up the database 3) Perform any operating system specific steps (optional). 4) Start up a new instance and mount but do not open the database.

To enable or disable archiving, the database must be mounted but not open.5)Switch the database's archiving mode.Enabling Automatic ArchivingIf your operating system permits, you can enable automatic archiving of the online redo log. Under this option, no action is required to copy a group after it fills; Oracle automatically archives groups after they are filled.Enabling Automatic Archiving at Instance StartupLOG_ARCHIVE_START=TRUE (SET THIS IN INIT.ORA)Enabling Automatic Archiving After Instance StartupALTER SYSTEM ARCHIVE LOG START;Disabling Automatic Archiving at Instance StartupLOG_ARCHIVE_START=FALSEDisabling Automatic Archiving after Instance StartupALTER SYSTEM ARCHIVE LOG STOP;To manually archive a filled online redo log groupALTER SYSTEM ARCHIVE LOG ALL;Displaying Archiving Status InformationSELECT log_mode FROM sys.v$database;SELECT group#, archived FROM sys.v$log;ARCHIVE LOG LIST;

End of Part one.

PART2. ORACLE 8.0 VERSION.

NEW FEATURES AND UTILITIES IN ORACLE8.0Page 67

Page 68: Oracle Questions

Oracle_QuestionsPARTITION OF TABLESOracle8 introduces partitioning for tables.Introduction to Partitioning This section explains how partitioning can help you manage large tables and indexes in an Oracle database. What Is Partitioning? Partitioning addresses the key problem of supporting very large tables and indexes by allowing users to decompose them intosmaller and more manageable pieces called partitions.

Note: Oracle only supports partitioning for tables and indexes; it does not support partitioning of clustered tables and theirindexes, nor of snapshots.

All partitions of a table or index have the same logical attributes, although their physical attributes can be different. For example,all partitions in a table share the same column and constraint definitions; and all partitions in an index share the same indexcolumns. However, storage specifications and other physical attributes such as PCTFREE, PCTUSED, INITRANS, andMAXTRANS can vary for different partitions of the same table or index.

Each partition is stored in a separate segment. Optionally, you can store each partition in a separate tablespace, which has thefollowing advantages:

You can contain the impact of damaged data. You can back up and recover each partition independently. You can balance I/O load by mapping partitions to disk drives.

Example of a Partitioned Table

In Figure 8-1, the sales table contains historical data divided by week number into 13 four-week partitions. This SQLstatement creates the partitioned table: CREATE TABLE sales ( acct_no NUMBER(5), acct_name CHAR(30), amount_of_sale NUMBER(6), week_no INTEGER ) PARTITION BY RANGE ( week_no ) ... (PARTITION VALUES LESS THAN ( 4 ) TABLESPACE ts0, PARTITION VALUES LESS THAN ( 8 ) TABLESPACE ts1, ... PARTITION VALUES LESS THAN ( 52 ) TABLESPACE ts12); Figure 8-1: SALES Table Partitioned by

Advantages of Partitioning

The following sections identify the classes of databases that could benefit from theuse of partitioning, and characterize them interms of the problems they present:

Very Large Databases (VLDBs) Reducing Downtime for Scheduled Maintenance Reducing Downtime Due to Data Failures

Page 68

Page 69: Oracle Questions

Oracle_Questions DSS Performance I/O Performance Disk Striping: Performance vs. Availability Partition Transparency Manual Partitioning with Partition Views

Very Large Databases (VLDBs)

A Very Large Database (VLDB) contains hundreds of gigabytes or even a few terabytes of data. Partitioning providessupport for VLDBs that contain mostly structured data, rather than unstructured data. These VLDBs typically owe their size tothe presence of a few very large data objects (tables and indexes) rather than to the presence of a very large number of dataobjects.

There are two major categories of VLDB:

On-Line Transaction Processing (OLTP) databases are designed for large numbers of concurrent transactions, where each transaction is a relatively simple operation processing a small amount of data. Decision Support Systems (DSS) are designed for very complex queries that need to access and process large amounts of data.

A VLDB may be characterized as an OLTP database if most of its workload is OLTP. Similarly a VLDB may becharacterized as a DSS database if most of its workload consists of DSS queries.

Partitioning efficiently supports both OLTP VLDBs and DSS VLDBs.

Historical Databases

Historical databases are the most common type of DSS VLDB. A historical database contains two classes of tables, historicaltables and enterprise tables.

Historical tables describe the business transactions of an enterprise over a recent time interval, such as the last 24 months. There are two types of historical tables: Base tables contain the baseline information (for example, sales, checks, and orders). Rollup tables contain summary information derived from the base information using operations such as GROUP BY, AVERAGE, and COUNT.

The time interval reflected in a historical table is a rolling window, so periodically the DBA deletes the set of rows describing the oldest transactions and allocates space for the set of rows describing new transactions. For example, at the close of business on April 30, 1997 the DBA deletes the rows (and all supporting index entries) that describe May 1995 transactions and allocates space for May 1997 transactions.

The vast majority of data in a historical VLDB is stored in few very large historical tables that present special problems due to their size and the requirement to smoothly roll out old data and roll in new data. Enterprise tables describe the business entities of the enterprise (for example, departments, locations, and products). This information changes slowly over time and is not modified on a periodic

Page 69

Page 70: Oracle Questions

Oracle_Questionsschedule. Although enterprise tables are not large, they affect the performance of many long-running DSS queries that consist of joins of a historical table with enterprise tables. Partitioning addresses the problem of supporting large historical tables and their indexes by dividing historical data intotime-related partitions that can be managed independently and added or deleted conveniently. Mission-Critical DatabasesMission-critical OLTP databases present special availability and performance problems even if they are not very large. Forexample, it may be necessary to perform scheduled maintenance operations or recover a 10-gigabyte table in a very shortperiod of time, perhaps an hour or less. Also, the DBA may need a degree of control over data placement that is hard toachieve when a table or index is spread over multiple drives. Partitioning can increase the availability of mission-critical databases if criticaltables and indexes are divided into partitions toreduce the maintenance windows, recovery times, and impact of failures. You can alsoimprove access performance to acritical table or index by controlling performance parameters on a partition basis.

Reducing Downtime for Scheduled Maintenance Partitioning can significantly reduce the impact of scheduled downtime for maintenance operations: By introducing partition maintenance operations that operate on an individual partition rather than on an entire table or index. By providing partition independence so that maintenance operations can be performed concurrently on different partitions.

Partition Maintenance OperationsPartition maintenance operations are faster than full table or index maintenance operations. A speedup can be achievedequal to the ratio: (# records in full table or index) / (# records in partition) provided there are no inter-partition stored constructs (global indexes and referential integrity constraints). To further reduce downtime, a partition maintenance operation can take advantage of performance features that are availablefor table and index-level maintenance operations, such as the PARALLEL, NOLOGGING, and DIRECT (or APPEND)options where applicable. Partition IndependencePartition independence for the partition maintenance operations makes it possible toperform concurrent maintenanceoperations on different partitions of the same table or index, as well as concurrentSELECT and DML operations againstpartitions that are unaffected by maintenance operations. For example, you can Direct Path Load into partitions PA and PB at the same time, while applications are executing standardSQL SELECT and DML operations against other partitions. Partition independence is particularly important for operations that involve data movement. Such operations may take a longtime (minutes, hours, or even days). Partitioning can reduce the window of unavailability on other partitions to a short time (fewseconds) during operations that involve data movement, provided there are no inter-partition stored constructs (global indexesand referential integrity constraints). Partition independence is not needed for short operations (no data movement) becausethese operations complete in a shorttime. Reducing Downtime Due to Data Failures Some maintenance operations are unplanned events, required to recover from hardware

Page 70

Page 71: Oracle Questions

Oracle_Questionsor software failures that cause dataloss or corruption. Recovery from hardware failures and many system software failures is accomplished by running theRECOVER command on a database, tablespace, or datafile. Any tables or indexes that have records in a tablespace ordatafile being recovered remain unavailable during recovery. Increased availability is particularly important for mission-criticalOLTP databases. Storing partitions in separate tablespaces provides the following benefits: Downtime due to execution of the RECOVER command is reduced because the unit ofrecovery (a tablespace) is smaller. Disk resources needed for recovery of an offline tablespace (deferred rollback segments) are reduced because the unit of recovery is smaller. The amount of unavailable data is reduced, because only the partition(s) storedin the recovered tablespace have to be taken offline. User applications and maintenance operations can still access the other partitions. This is another example of partition independence. DSS Performance DSS queries on very large tables present special performance problems. An ad-hoc query that requires a table scan may take a long time, because it must inspect everyrow in the table; there is no way to identify and skip subsets of irrelevant rows. The problem is particularly important for historical tables, for which many queries concentrate access on rows that were generated recently.

Partitions help solve this DSS performance problem. An ad-hoc query which only requires rows that correspond to a singlepartition (or range of partitions) can be executed using a partition scan rather than a table scan. For example, a query that requests data generated in the month of October 1997 can scan just the rows stored in the October 1997 partition, rather than rows generatedover many years of activity. This improves response time and it may also substantially reduce the temporary disk space requirement for queries that require sorts.I/O Performance Partitioning can control how data is spread across physical devices. To balance I/O utilization, you can specify where to store the partitions of a table or index. With this level of location control, you can accommodate the special needs of applications that require fast response time by reducing disk contention and using faster devices. On the other hand, data that is accessed infrequently, such as old historicaldata, can be moved to slow disks or stored in subsystems that support a storage hierarchy.

Disk Striping: Performance vs. AvailabilityDisk striping and partitioning are both tools that can improve performance through the reduction of contention for disk arms.Which tool to use, or in which proportions to use them together, is an important issue to consider when physically designing databases. These issues should be considered not only with respect to performance, but also with respect to availability and partition independence. Figure 8-2 "Partitions and Disk Striping" on page 8-8 shows the two extremes of combining partitioning and striping. Both (a) and (b) show four partitions spread across eight disks, but (a) stripes each partition onto its own pair of disks, whereas (b)stripes each partition onto all eight disks. The performance characteristics are better in (b), but if any single disk failure occurs, all partitions are adversely affected. The availability characteristics are better in (a), because failure of a singledisk only affects one partition. Intermediate configurations are also possible, where subsets of partitions are striped over subsets of disks.

Figure 8-2: Partitions and Disk StripingPage 71

Page 72: Oracle Questions

Oracle_Questions

The trade-off between performance and availability must be decided when determining how to partition tables and indexes, andhow to stripe the disks they reside on. For mission-critical databases it is recommended that partition independence and availability be favored, therefore eachpartition that you want to stripe across disks should be striped onto its own set ofdisk drives. The set of disks should includeenough drives to achieve the required I/O parallelism for accesses to a given partition. Partition Transparency The vast majority of application programs require partition transparency, that is the programs should be insensitive to whetherthe data they access is partitioned and how it is partitioned. A few application programs, however, can take advantage of partitions by explicitly requesting access to an individual partition,rather than the entire table. For example, a user might want to break a long batch job on a very large table into a sequence ofshort nightly batch jobs on individual partitions.

Manual Partitioning with Partition Views

You can also build separate tables with identical templates, and define a view (partition view) that does a UNION of thesetables. This is known as manual partitioning. You must create a UNION ALL view over all the base tables to support access to the logical table and to provide a degree ofpartition transparency. You can then define sets of "base indexes" with identical key specifications on the base tables, toprovide indexing capabilities when the UNION ALL view is used. Manual partitioning with partition views has a number of disadvantages: Configuration complexity The user is responsible for correctly defining the base tables and indexes thatcorrespond to partitions, and for maintaining these definitions. The equivalent of DDL operations that move data across partitions (split, move, etc.) must be implemented via Export/Import or SQL scripts. Lack of partition transparency Some SQL operations must be performed using the base tables rather than the UNION ALL view. For example, INSERT refers to a base table, and user code is needed to obtain the table namethat appears in an INSERT statement. Lack of performance Some SQL operations on the UNION ALL view may perform badly because the optimizer does not take advantage of all the existing base indexes. Poor memory utilization

A SQL compiled query operating on a UNION ALL view internally replicates descriptive information for all tables that support the view. DDL restrictions Global indexes and referential integrity constraints cannot be defined on the UNION ALL view. Load restrictions It is not possible to perform direct loads on a UNION ALL view. For more information about partition views, see "Partition Views" on page 7-14. Basic Partitioning Model This section describes the basic model for a partitioned table or index, and how youcan use this model to create a range-partitioned table or index.

Page 72

Page 73: Oracle Questions

Oracle_QuestionsPartitioning is specified with new options to the CREATE TABLE and CREATE INDEX statements. After creating a partitioned table or index, you can use ALTER TABLE or ALTER INDEX statements to modify its partitioning attributes. The partitioning syntax for CREATE TABLE and CREATE INDEX statements is very similar. The CREATE TABLE statement specifies: 1.The logical attributes of the table, such as column and constraint definitions.

2.The physical attributes of the table. If the table is non-partitioned, these are the real physical attributes ofthe segment associated with the table. If the table is partitioned, these table-level attributes specify defaultsfor the individual partitions of the table. 3.For a partitioned table, there is also a partition specification which includes: the table-level algorithm used to map rows to partitions a list of partition descriptions, one for each partition in the table.

Each partition description includes a clause which defines supplemental, partition-level information about the algorithm used to map rows to partitions. It also includes, optionally, a partition name and physical attributes for the partition. Datatype Restrictions For partitioned tables, the logical attributes have additional restrictions. Partitioned tables cannot have any columns with LONG or LONG RAW datatypes, LOB datatypes (BLOB, CLOB, NCLOB, or BFILE), or object types. Bitmap Restrictions Like other indexes, you can create bitmap indexes on partitioned tables. The only restriction is that bitmap indexes must belocal to the partitioned table-they cannot be global indexes. (See "Index Partitioning" on page 8-19 for information about localindexes.) Cost Based Optimization Partitioned tables use the cost based optimizer; they do not use the rule based optimizer. Statistics can be gathered by partition.It is important to gather statistics whenever the nature of the data in a partitioned table changes significantly.

The statistics can be found in these data dictionary views: ALL_TAB_PARTITIONS, DBA_TAB_PARTITIONS, USER_TAB_PARTITIONS ALL_IND_PARTITIONS, DBA_IND_PARTITIONS, USER_IND_PARTITIONS ALL_PART_COL_STATISTICS, DBA_PART_COL_STATISTICS, USER_PART_COL_STATISTICS Range Partitioning Range partitioning maps rows to partitions based on ranges of column values. Range partitioning is defined by the partitioning specification for a table or index: PARTITION BY RANGE ( column_list ) and by the partitioning specifications for each individual partition: VALUES LESS THAN ( value_list ) here: column_list is an ordered list of columns that determines the partition to which a row or an index entry belongs. These columns are called the partitioning columns. The values in the partitioning columns of a particular row constitute thatrow's partitioning key. value_list is an ordered list of values for the columns in column_list. Each value in value_list must be either a literal or a TO_DATE() or RPAD()function with constant arguments. The value_list contained in the partitioning specification for the ith partition defines an open (non-inclusive) upper bound for the partition, referred to as the partition bound. The partition bound for the ith partition defines an open (non-inclusive) upper bound for the partition. The partition bound for the ith partition must compare less than the partition bound for the (i+1)th partition.

In the ith partition, all rows (or rows pointed to by index entries) have partitioning keys that compare less than the partition bound for that partition.

Page 73

Page 74: Oracle Questions

Oracle_QuestionsUnless the ith partition is the first partition in the table or index, all of the partitioning keys in the ithpartition also compare greater than or equal to the partition bound for the (i-1)th partition. (See "Partition Bounds and Partitioning Keys" on page 8-13 for more information about how partitioning keys are compared to partition bounds, and in particular how multi-column partitioning keys are handled.) For example, in the following table of four partitions (one for each quarter's sales), a row with sale_year=1997,sale_month=7, and sale_day=18 has partitioning key (1997, 7, 18), belongs in the third partition, and would be stored in tablespace tsc. A row with sale_year=1997, sale_month=7, and sale_day=1 has partitioning key (1997, 7, 1), and also belongs in the third partition, stored in tablespace tsc. CREATE TABLE sales ( invoice_no NUMBER, sale_year INT NOT NULL, sale_month INT NOT NULL, sale_day INT NOT NULL ) PARTITION BY RANGE( sale_year, sale_month, sale_day) ( PARTITION sales_q1 VALUES LESS THAN( 1994, 04, 01) TABLESPACE tsa, PARTITION sales_q2 VALUES LESS THAN( 1994, 07, 01) TABLESPACE tsb, PARTITION sales_q3 VALUES LESS THAN( 1994, 10, 01) TABLESPACE tsc, PARTITION sales_q4 VALUES LESS THAN( 1995, 01, 01) TABLESPACE tsd ) Partition Names Every partition has a name. Partition names must conform to the usual rules for naming schema objects and their parts (seeOracle8 Server SQL Reference). In particular: The name of a table partition must be unique among all the partitions belongingto the same parent table. The name of an index partition must be unique among all the partitions belonging to the same parent index. You can rename a partition; however, you cannot create a synonym on a partition name. Referencing a PartitionPartition names can optionally be referenced in DDL and DML statements and in utility statements like Import/Export andSQL*Loader. They always appear in context with the name of their parent table or index and they are never qualified by a schema name. (The schema name can be used toqualify the parent table or index.) For example: ALTER TABLE admin.patient_visits DROP PARTITION pv_dec92 Partition Bounds and Partitioning Keys This section describes how a row's partitioning key is compared with a set of upper and lower bounds to determine which partition the row belongs in. Partition BoundsEvery table and index partition has a non-inclusive upper bound, which is specified by the VALUES LESS THAN clause.Every partition except the first partition also has alower bound (inclusive), which is specified by the VALUES LESS THANon the next-lowerpartition. The partition bounds collectively define an ordering of the partitions in a table orindex. The "first" partition is the partition with the lowest VALUES LESS THAN clause, and the "last" or "highest" partition is the partition with the highest VALUES LESSTHAN clause. If you attempt to insert a row into a table and the row's partitioning key is greater than or equal to the partition bound for the highest partition in the table,the insert will fail. Partitioning KeysA partitioning key consists of an ordered list of up to 16 columns. A row's partitioning key is an ordered list of its values for the partitioning columns. A partitioning key may not contain the LEVEL, ROWID, or MLSLABEL pseudocolumn or a column of type ROWID. When comparing character values in partitioning keys and partition bounds, characters are compared according to their binary values. The comparison also uses the comparison rules associated with the column data type (for example, blank-paddedcomparison is done for the ANSI CHAR data type). The NLS parameters, specifically the NLS_LANG, NLS_SORT, and NLS_LANGUAGE

Page 74

Page 75: Oracle Questions

Oracle_Questionsparameters, have no effect on the comparison. MAXVALUEYou can specify the keyword MAXVALUE for any value in the partition bound value_list. This keyword represents a virtual "infinite" value that sorts higher than any other value for the data type, including the null value. For example, you might partition the office table on state (a CHAR(10) column) into three partitions with the following partition bounds: VALUES LESS THAN ( `I' ): Contains states whose names start with A through H. VALUES LESS THAN ( `S' ): Contains states whose names start with I through R. VALUES LESS THAN ( MAXVALUE ): Contains states whose names start with S throughZ, plus special codes for non-U.S. regions. NullsNULL cannot be specified as a value in a partition bound value_list. An empty stringalso cannot be specified as a value in apartition bound value_list, because it is treated as NULL within the database server. For the purpose of assigning rows to partitions, Oracle sorts nulls greater than allother values except MAXVALUE. Nulls sortless than MAXVALUE. This means that if a table is partitioned on a nullable column, and the column is tocontain nulls, then the highest partition should have a partition bound of MAXVALUE for that column. Otherwise the rows that contain nulls will map above the highestpartition in the table and the insert will fail. Multi-Column Partitioning KeysWhen a table or index is partitioned on multiple columns, each partition bound and partitioning key is a list (or vector) of values.In this case, the keys are ordered according to ANSI SQL2 vector comparison rules (this is also the way multi-column index keys are ordered in Oracle). For vectors V1and V2 which contain the same number of values, Vx[i] is the ith value in Vx. assuming that V1[i] and V2[i] have compatible data types: V1 = V2 if and only if V1[i] = V2[i] for all i. V1 < V2 if and only if V1[i] = V2[i] for all i < n and V1[n] < V2[n] for some n. V1 > V2 if and only if V1[i] = V2[i] for all i < n and V1[n] > V2[n] for some n. In plain English, if you want to know if a partitioning key PK is less than or equalto partition bound PB, you compare corresponding values in PK and PB until you find a pair that is not equal and that pair decides. For example, if the partition bound for partition P is (7, 5, 10) and the partition bound for the next lowest partition is (6, 7, 3) then: Keys (6, 9, 11) and (7, 3, 15) belong in partition P, because: key (6, x, x) is less than (7, x, x), and (6, 9, x) is greater than (6, 7,x) key (7, 3, x) is less than (7, 5, x) and greater than (6, 7, x) Keys (6, 5, 0) and (7, 5, 11) belong in other partitions. If MAXVALUE appears as an element of a partition bound value_list, then the values of all the following elements are irrelevant. For example, a partition bound of (10,MAXVALUE, 5) is equivalent to a partition bound of (10, MAXVALUE, 6)or to a partition bound of (10, MAXVALUE, MAXVALUE). Multi-column partitioning keys are useful when the primary key for the table contains multiple columns, but rows are not distributed evenly over the most significant column in the key. For example, suppose that the supplier_parts table contains information about which suppliers provide which parts, and the primary key for the table is (suppnum, partnum). It is not sufficient to partition on suppnum because some suppliers provide hundreds of thousands of parts, while others provide only a few specialty parts. Instead, you can partition the table on (suppnum, partnum). Multi-column partitioning keys are also useful when you represent a date as three CHAR columns instead of a DATE column. Implicit Constraints Imposed by Partition BoundsIf you specify a partition bound other than MAXVALUE for the highest partition in a table, this imposes an implicit CHECK constraint on the table. This constraint is not recorded in the data dictionary (but the partition bound itself is recorded).

Page 75

Page 76: Oracle Questions

Oracle_QuestionsEqui-Partitioning Two tables or indexes are equi-partitioned if they have identical logical partitioning attributes. They do not have to be the same type of schema object; for example, a table and an index can be equi-partitioned. If A and B are partitioned tables or indexes, where A[i] is the ith partition in A and B[i] is the ith partition in B, then A and B are equi-partitioned if all of the following are true: They have the same number of partitions N. They have the same number of partitioning columns M. For every 1 <= i <= N, A[i] and B[i] have the same partition bound. If Apcol[i] is the ith partitioning column in A and Bpcol[i] is the ith partitioningcolumn in B, then the following must also be true: For 1 <= i <= M, Apcol[i] and Bpcol[i] have the same data type, including length, precision, and scale. A[i] and B[i] may differ in their physical attributes; in particular they do not have to reside in the same tablespace. Equi-partitioning is important to consider when designing the database. It reduces the downtime and the amount of data that is unavailable during partition maintenance operations and tablespace recovery operations. For example, if a table and its local indexes are equi-partitioned then the effect of splitting a partition can be limited to one table partition and the corresponding index partitions. (See "Index Partitioning" on page 8-19 for information about local indexes.) It improves execution plans by reducing the number of large sorts and joins that have to be performed. It makes tablespace incomplete recovery (point-in-time recovery) on related subsets of data easier. For example, you might equi-partition a table and its primary key index, or a parent table and a child table. You could then recover corresponding partitions to a point in time. Example of Equi-PartitioningFigure 8-3 "Equi-Partitioned Tables and Indexes" on page 8-17 shows four logically related schema objects that are equi-partitioned: ACCOUNTS is a table with two partitions which is range-partitioned on column ACCOUNT_NO. The first partition contains account numbers up to 1000. The second partition contains account numbers up to 2000. ACCOUNTS_IX is an index on column ACCOUNT_NO in the ACCOUNTS table. Like the table, the index is range-partitioned on ACCOUNT_NO into two partitions, which have the same partition bounds as partitions of ACCOUNTS. CHECKS is a table with two partitionswhich is range-partitioned on column ACCT_NO. Its partitions have the same partition bounds as partitions of the ACCOUNTS table. ACCT_NO is a foreign key that references ACCOUNT_NO in ACCOUNTS. CHECKS_IX is an index on columns (ACCT_NO, CHECK_NO) in CHECKS. It is range-partitioned on ACCT_NO into two partitions, which have the same partition bounds as partitions of ACCOUNTS. The logical relationship between the four schema objects is shown on the left; the physical partitioning is shown on the right.(Triangles represent indexes and rectanges represent tables.) Figure 8-3: Equi-Partitioned Tables and IndexesRules for Partitioning Tables and Indexes

This section describes the rules for creating partitioned tables and indexes and thephysical attributes of partitions. Table Partitioning The rules for partitioning tables are simple: A table can be range-partitioned, provided that: It is not part of a cluster. It does not contain LOBs, LONG or LONG RAW datatypes, or object types. It is not an index-organized table. You can mix partitioned and non-partitioned indexes with partitioned and non-partitioned tables: A partitioned table can have partitioned and/or non-partitioned indexes. A non-partitioned table can have partitioned and/or non-partitioned indexes. (Only global indexes can be created on non-partitioned tables-see "Global

Page 76

Page 77: Oracle Questions

Oracle_QuestionsIndexes" on page 8-22.) Physical Attributes of Table PartitionsDefault physical attributes are initially specified when the CREATE TABLE statement creates a partitioned table. Since there is no segment corresponding to the partitioned table itself, these attributes will only be used in derivation of physical attributes ofmember partitions. Default physical attributes can later be modified using ALTER TABLE MODIFY DEFAULTATTRIBUTES.

Physical attributes of table partitions created by CREATE TABLE and ALTER TABLE ADD PARTITION are determined as follows: Values of physical attributes specified (explicitly or by default) for the basetable are used whenever the value of a corresponding partition attribute was not specified. Physical attributes of an existing table partition may be modified by ALTER TABLE MOVE PARTITION and ALTERTABLE MODIFY PARTITION. Resulting attributes are determined as follows: Values of physical attributes of the partition before the statement was issued are used whenever a new value was not specified. Note that ALTER TABLE MOVE PARTITION may be used to change the tablespace in which a partition resides. Physical attributes of table partitions created by ALTER TABLE SPLIT PARTITION are determined as follows: Values of physical attributes of the partition being split are used whenever a new value was not specified. (This also applies to global index split - missing attributes are inherited from the index partition being split.) Physical attributes of all partitions of a table may be modified by ALTER TABLE, forExample, ALTER TABLE tablename NOLOGGING changes the logging mode of all partitions of tablename to NOLOGGING. PARTITION INDEXESIndex Partitioning The rules for partitioning indexes are similar to those for tables: An index can be range-partitioned with these exceptions: The index is not a cluster index. The index is not defined on a clustered table. A bitmap index on a partitioned table must be a local index. You can mix partitioned and non-partitioned indexes with partitioned and non-partitioned tables: A partitioned table can have partitioned and/or non-partitioned indexes. A non-partitioned table can have partitioned and/or non-partitioned B*-tree indexes. Bitmap indexes on non-partitioned tables cannot be range-partitioned. However, partitioned indexes are more complicated than partitioned tables because there are four types of range-partitioned indexes: local prefixed, local non-prefixed, global prefixed, and global non-prefixed. These types are described below. Oraclesupports three of the four types (global non-prefixed indexes are not useful in realapplications). Local IndexesIn a local index, all keys in a particular index partition refer only to rows storedin a single underlying table partition. A localindex is created by specifying the LOCAL attribute. The Oracle Server constructs the local index so that it is equi-partitioned with theunderlying table. Oracle range-partitions the index on the same columns as the underlying table, creates the same number of partitions, and gives them the same partitionbounds as corresponding partitions of the underlying table. Oracle also maintains the index partitioning automatically as partitions in the underlying table are added, dropped, or split. This ensures that the index remains equi-partitioned with thetable. Equi-partitioning a table and its index has the following advantages: Only one index partition is affected when a maintenance operation (other than

Page 77

Page 78: Oracle Questions

Oracle_QuestionsSPLIT PARTITION) is performed on anunderlying table partition. The duration of a partition maintenance operation remains proportional to partition size if the partitioned table has only local indexes. Local indexes support partition independence. Local indexes support smooth roll-out of old data and roll-in of new data in historical tables. Oracle can take advantage of the fact that a local index is equi-partitioned with the underlying table to generate better query access plans. Local indexes simplify the task of tablespace incomplete recovery. In order to recover a partition of a table to a point in time, you must also recover the corresponding index entries to the same point in time. The only way to accomplish this is with a local index; then you can recover the corresponding table and index partitions together. Local Prefixed IndexesA local index is prefixed if it is partitioned on a left prefix of the index columns. For example, if the sales table and its local index sales_ix are partitioned on the week_num column, then index sales_ix islocal prefixed if it is defined on the columns (week_num,xaction_num). On the other hand, if index sales_ix is defined oncolumn product_num then it is not prefixed. (See Figure 8-4 "Local Prefixed Index" for another example.) Local prefixed indexes can be unique or non-unique. Figure 8-4: Local Prefixed Index

Local Non-Prefixed IndexesA local index is non-prefixed if it is not partitioned on a left prefix of the indexcolumns. You cannot have a unique local non-prefixed index unless the index key is a subset of the partitioning key. Figure 8-5: Local Non-Prefixed Index

Global IndexesIn a global index, the keys in a particular index partition may refer to rows storedin more than one underlying table partition.A global index is created by specifying the GLOBAL attribute (this is the default). The user is responsible for defining theinitial partitioning of a global index at creation and for maintaining the partitioning over time. Index partitions can be dropped or split as necessary. Normally, a global index is not equi-partitioned with the underlying table. There isnothing to prevent an index from being equi-partitioned with the underlying table, but Oracle does not take advantage of the equi-partitioning when generating query plans or executing partition maintenance operations. So an index that is equi-partitioned with the underlying table should be created as LOCAL. A global index contains (conceptually) a single B+-tree with entries for all rows inall partitions. Each index partition may contain keys that refer to many different partitions in the table. The highest partition of a global index must have a partition bound all of whose values are MAXVALUE. This insures that all rows in the underlying table can be represented in the index. A global index is prefixed if it is partitioned on a left prefix of the index columns. (See Figure 8-6 "Global Prefixed Index" on page 8-23.) A global index is non-prefixed if it is not partitioned on a left prefix of the index columns. Oracle does not support global non-prefixed indexes. Global prefixed indexes can be unique or non-unique. Global indexes are harder to manage than local indexes: When the data in an underlying table partition is moved or removed (SPLIT, MOVE, DROP, or TRUNCATE), all partitions of a global index are affected. Consequently global indexes cause partition maintenance (including rebuilds of global indexes or index partitions) to have duration proportional to table size rather than partition size, and they do not support partition independence. When an underlying table partition is recovered to a point in time, all corresponding entries in a global index must be recovered to the same point in time.

Page 78

Page 79: Oracle Questions

Oracle_QuestionsBecause these entries may be scattered across all partitions of the index (mixed in with entries for other partitions that are not being recovered), there is no way to accomplish this except by recreating the entire global index. Non-partitioned indexes are treated as global prefixed indexes. Figure 8-6: Global Prefixed Index

Summary of Partitioned Index TypesThe table below summarizes the three types of partitioned indexes that are supportedby Oracle. If an index is local, it is equi-partitioned with the underlying table; otherwise it is global. A prefixed index is partitioned on a left prefix of the index columns; otherwise it is non-prefixed. Table 8-1: Types of Partitioned Indexes Type of Index Index Equi-Partitioned with Table Index Partitioned on Left Prefix of Index Columns UNIQUE Attribute Allowed Example Table Par-titioned On Index Columns Index Par-titioned On Local Prefixed Y Y Y A A,B A Local Non-Prefixed Y N Y1 A B A Global

Prefixed N2 Y Y A B B Global Non-Prefixed

Page 79

Page 80: Oracle Questions

Oracle_Questions Not Supported

1 For a unique local non-prefixed index, the index key must be a subset of the partitioning key. 2 Although a global partitioned index may be equi-partitioned with the underlying table, Oracle does not take advantage of the partitioning or maintain equi-partitioning after partition maintenance operations such as DROP or SPLIT PARTITION.Importance of Non-Prefixed Indexes Non-prefixed indexes are particularly useful in historical databases. In a table containing historical data it is common for anindex to be defined on one column to support the requirements of fast access by thatcolumn, but partitioned on another column (the same column as the underlying table) to support the time interval for rolling out old data and rolling in new data.

Consider the sales table presented in Figure 8-1 "SALES Table Partitioned by Week" on page 8-3. It contains a year's worth of data, divided into 13 partitions. It is range partitioned on week_no, four weeks to a partition. The user might create anon-prefixed local index sales_ix on sales. The sales_ix index is defined on acct_nobecause there are queries that need fast access to the data by account number. However it is partitioned on week_no to match the sales table. Every four weeks theoldest partitions of sales and sales_ix are dropped and new ones are added. Performance Implications of Prefixed and Non-Prefixed IndexesIt is more expensive to scan a non-prefixed index than to scan a prefixed index. If an index is prefixed (either local or global) and Oracle is presented with a predicate involving the index columns, then Oracle can restrict application of the predicate to a subset of the index partitions. For example, in Figure 8-4 "Local Prefixed Index" on page 8-21, if the predicate is DEPTNO=15, the optimizer knows to apply the predicate only to the second partition of the index. (If the predicate involves a bind variable, the optimizer will not know exactly which partition but itmay still know there is only one partition involved, in which case at run time only one index partition will be accessed.) When an index is non-prefixed Oracle must apply a predicate involving the index columns to all N index partitions. This is required to look up a single key, or to do an index range scan. In the case of a range scan, Oracle must also combine information from N index partitions. Of course, if there is also a predicate on the partitioning columns then multiple index probes might not be necessary. For example, in Figure 8-5 "Local Non-Prefixed Index" on page 8-22, if the predicateis ACCTNO=31, Oracle probes all 12 index partitions. The fact that many queries and DML statements using keys of local, non-prefixed, indexes have to probe all index partitions effectively reduces the degree of partition independence provided by such indexes. Guidelines for Partitioning IndexesWhen deciding how to partition indexes on a table, you must consider the mix of applications that need to access the table. There is a trade-off between performanceon the one hand and availability and manageability on the other. Here are some ofthe guidelines you should consider: For OLTP applications: Global indexes and local prefixed indexes provide better performance than local non-prefixed indexes because they minimize the number of index probes. Local indexes support more availability when there are partition maintenance operations on the table. Local non-prefixed indexes are very useful for historical databases. For DSS applications, local non-prefixed indexes can improve performance because many index partitions can be scanned in parallel by range queries on the index key. For example, a query using the predicate "ACCTNO between 40 and 45" on the table CHECKS of Figure 8-5"Local Non-Prefixed Index" on page 8-22 causes parallel scans of all the partitions of the non-prefixed index IX3. On the other hand, a query using the predicate "DEPTNO between 40 and 45" on the table DEPTNO of Figure 8-4 "Local Prefixed Index" on page 8-21 cannot be parallelized because it accesses a single partition of the prefixed index IX1. For historical tables, indexes should be local if possible. This limits the impact of regularly scheduled drop partition operations. Unique indexes on columns other than the partitioning columns must be global because unique local non-prefixedindexes whose key does not contain the partitioning key are not supported. Physical

Page 80

Page 81: Oracle Questions

Oracle_QuestionsAttributes of Index PartitionsDefault physical attributes are initially specified when CREATE INDEX statement is used to create a partitioned index. Since there is no segment corresponding to the partitioned index itself, these attributes will only be used in derivation of physicalattributes of member partitions. Default physical attributes can later be modified using ALTER INDEX. Physical attributes of partitions created by CREATE INDEX are determined as follows:

Values of physical attributes specified (explicitly or by default) for the index are used whenever the value of a corresponding partition attribute was not specified. Handling of the TABLESPACE attribute of partitions of a LOCAL index constitutes an important exception to this rule in that in the absence of a user-specified TABLESPACE value, that of the corresponding partition of the underlying table will be used. Physical attributes (other than TABLESPACE, as explained above) of partitions of local indexes created in the course of processing ALTER TABLE ADD PARTITION are set to thedefault physical attributes of each index. Physical attributes (other than TABLESPACE, as explained above) of index partitions created by ALTER TABLE SPLIT PARTITION are determined as follows:

Values of physical attributes (other than TABLESPACE, as explained above) of the index partition being split are used. Physical attributes of an existing index partition can be modified by ALTER INDEX MODIFY PARTITION and ALTER INDEX REBUILD PARTITION. Resulting attributes are determined as follows: Values of physical attributes of the partition before the statement was issued are used whenever a new value was not specified. Note that ALTER INDEX REBUILD PARTITION can be used to change the tablespace in which a partition resides. Physical attributes of global index partitions created by ALTER INDEX SPLIT PARTITION are determined as follows: Values of physical attributes of the partition being split are used whenever a new value is not specified. Physical attributes of all partitions of an index may bemodified by ALTER INDEX, for example, ALTER INDEX indexname NOLOGGING changes the logging mode of all partitions of indexname to NOLOGGING.

PARTITION VIEWSThe database administrator can use partition views to divide a very large table intomultiple smaller pieces (or partitions) to achieve significant improvements in availability, administration, and performance. The basic idea behind partition viewsis simple: divide the large table into multiple physical tables using a partitioningcriteria;glue the partitions together into a whole for query purposes. A partition view can assign key ranges to partitions. Queries thatuse a key range to select froma partitions view will access only the partitions that lie within the key range.Benefits of Partition Views Partition views enable data management operations like data loads, index creation, and data purges at the partition level, rather than on the entire table, resulting in significantly reduced times for these operations. Because the partitions are independent of each other, unavailability of a piece (or a subset of pieces) does not affect access to the ret of the data.OBJECT VIEWSIn the Oracle object-relational database, object views allow you to retrieve, update, insert, and delete relational data as if they were stored as object types. You can also define views that have columns which are object datatypes, such as objects, REFs,and collections (nested tables and VARRAYs).Just as a view is a virtual table, an object view is a virtual object table. Oracle provides object views as an extension of the basic relational view mechanism.By using object views, you can create virtual object tables from data-of either built-in or user-defined types-stored in the columns of relational or object tables in thedatabase. Object views provide the ability to offer specialized or restricted access to the

Page 81

Page 82: Oracle Questions

Oracle_Questionsdata and objects in a database. For example, you might use an object view to providea version of an employee object table that doesn't have attributes containing sensitivedata and doesn't have a deletion method. Object views allow use of relational data in object-oriented applications. They let users Try object-oriented programming techniques without converting existing tables. Convert data gradually and transparently from relational tables to object-relational tables. Use legacy RDBMS data with existing object-oriented applications. Advantages of Object Views Using object views can lead to better performance. Relational data that make up a row of an object view traverse the networkas a unit, potentially saving many round trips. You can fetch relational data into the client-side object cache and map it into C orC++ structures so 3GL applications can manipulate it just like native structures. Object views provide a gradual migration path for legacy data. Object views provide for co-existence of relational and object-oriented applications. They make it easier to introduce object-oriented applications to existing relational data without having to make a drastic change from one paradigm to another. Object views provide the flexibility of looking at the same relational or object data in more than one way. Thus you can use different in-memory object representations for different applications without changing the way you store the data in thedatabase. Defining Object Views Conceptually, the procedure for defining an object view is simple: 1.Define an object type to be represented by rows of the object view. 2.Write a query that specifies which data in which relational tables contain the attributes for objects of that type. 3.Specify an object identifier, based on attributes of the underlying data, to allow REFs to the objects (rows) of the object view. The object identifier corresponds to the unique object identifier that Oracle generates automatically for rows of object tables. In the case of object views, however, the declaration must specify something that is unique in the underlying data (for example, aprimary key). If the object view is based on a table or another object view and you don't specify an object identifier, Oracle uses the object identifier from the original table or object view. If you wish to be able to update a complex object view, you may have to take anotherstep: 4.Write an INSTEAD OF trigger procedure (see "Updating Object Views" on page 12-4) for Oracle to execute whenever an application program tries to update data in the object view. After these steps you can use an object view just like an object table. For example, the following SQL statements define an object view: CREATE TABLE emp_table (empnum NUMBER (5),ename VARCHAR2 (20),salary NUMBER (9, 2),job VARCHAR2 (20) ) ;CREATE TYPE employee_t (empno NUMBER (5),ename VARCHAR2 (20),salary NUMBER (9, 2),job VARCHAR2 (20) ) ;CREATE VIEW emp_view1 OF employee_t WITH OBJECT OID (empno) ASSELECT e.empnum, e.ename, e.salary, e.job FROM emp_table eWHERE job = 'Developer' ;The object view looks to the user like an object table whose underlying type is employee_t. Each row contains an object of type employee_t. Each row has a unique object identifier. Oracle constructs the object identifier based on the specified key. In most cases itis the primary key of the base table. If the query that defines the object view involves joins, however, you must provide a key across all tables involved in the joins, so thatthe key still uniquely identifies rows of the object view. Note: Columns in the WITH OBJECT OID clause-empno in the example-must also be

Page 82

Page 83: Oracle Questions

Oracle_Questionsattributes of the underlying object type-employee_t in the example. This makes it easy for trigger programs to identify the corresponding row in the base table uniquely. Using Object Views Data in the rows of an object view may come from more than one table, but the objectstill traverses the network in one operation. When the instance is in the client side object cache, it appears to the programmer as a C or C++ structure or as a PL/SQL object variable. You can manipulate it like any other native structure. You can refer to object views in SQL statements the same way you refer to an object table. For example, object views can appear in a SELECT list, in an UPDATE-SET clause, or in a WHERE clause. You can also define object views on object views. You can access object view data on the client side using the same OCI calls you use for objects from object tables. For example, you can use OCIObjectPin() for pinning a REF and OCIObjectFlush() for flushing an object to the server. Whenyou update or flush to the server an object in an object view, Oracle updates the object view. See Programmer's Guide to the Oracle Call Interface, Volume I: OCI Concepts for additional information. Updating Object Views You can update, insert, and delete the data in an object view using the same SQL DMLyou use for object tables. Oracle updates the base tables of the object view if there is no ambiguity. A view is not updatable if its view query contains joins, set operators, group functions, GROUP BY, or DISTINCT. If a view query contains pseudocolumns or expressions, the corresponding view columns are not updatable. Object views often involve joins. To overcome these obstacles Oracle provides INSTEAD OF triggers (see Chapter 17, "Database Triggers"). They are called INSTEAD OF triggers because Oracle executes the trigger body instead of the actual DML statement. INSTEAD OF triggers provide a transparent way to update object views or relational views. You write the same SQL DML (INSERT, DELETE, and UPDATE) statements as for an object table. Oracle invokes the appropriate trigger instead of the SQL statement, and the actions specified in the trigger body take place.User-Defined Datatypes (Objects Option) This chapter describes features provided with the objects option.introduction Relational database management systems (RDBMSs) are the standard tool for managing business data. They provide fast,efficient, and completely reliable access to huge amounts of data for millions of businesses around the world every day. The objects option makes Oracle an object-relational database management system (ORDBMS), which means that users can define additional kinds of data-specifying both the structure of the data and the ways of operating on it-and use these types within the relational model. This approach adds value to the data stored in a database. Oracle with the objects option stores structured business data in its natural form and allows applications to retrieve it that way.For that reason it works efficientlywith applications developed using object-oriented programming techniques. Oracle's support for user-defined datatypes makes it easier for application developers to work with complex data like images,audio, and video. Complex Data Models The Oracle Server allows you to define complex business models in SQL and make them part of your database schema.Applications that manage and share your data need only contain the application logic, not the data logic. An ExampleFor example, your firm may use purchase orders to organize its purchasing, accounts payable, shipping, and accounts receivable functions. A purchase order contains an associated supplier or customer and an indefinite number of line items. In addition, applications often need dynamically computed status information about purchase orders. For example, you may need the current value of the shipped or unshipped line items. Later sections of this chapter show how you can define a schema object, called an object type, that serves as a template for all purchase order data in your applications. An object type specifies the elements, called attributes, that make upa structured data unit like a purchase order. Some attributes, such as the list of line items, may be other structured data units. The object type also specifies the

Page 83

Page 84: Oracle Questions

Oracle_Questionsoperations, called methods, you can perform on the data unit, such as determining the total value of a purchase order. You can create purchase orders that match the template and store them in table columns, just as you would numbers or dates. You can also store purchase orders in object tables, where each row of the table corresponds to a single purchase order and the table columns are the purchase order's attributes. Since the logic of the purchase order's structure and behavior is in your schema, your applications don't need to know the details and don't have to keep up with mostchanges. Oracle uses schema information about object types to achieve substantial transmission efficiencies. A client-side application can request a purchase order from the server and receive all the relevant data in a single trasmission. The application can then,without knowing storage locations or implementation details, navigate among related data items without further transmissions from the server. Multimedia DatatypesMany efficiencies of database systems arise from their optimized management of basicdatatypes like numbers, dates, and characters. Facilities exist for comparing values, determining their distributions, building efficient indexes, and performing otheroptimizations. Text, video, sound, graphics, and spatial data are examples of important business entities that don't fit neatly into those basic types. Oracle with the objects option supports modeling and implementation of these complex datatypes. User-Defined Datatypes Chapter 9, "Built-In Datatypes" describes Oracle's built-in datatypes. The objects option adds two categories of user-defined datatypes: object types and collection types.

User-defined datatypes use the built-in datatypes and other user-defined datatypes as the building blocks for datatypes that model the structure and behavior of data in applications. User-defined types are schema objects. Their use is subject to the same kinds of administrative control as other schema objects (see Chapter 11, "Using User-Defined Datatypes"). Object Types Object types are abstractions of the real-world entities-for example, purchase orders-that application programs deal with. An object type is a schema object with three kinds of components: A name, which serves to identify the object type uniquely within that schema. Attributes, which model the structure and state of the real world entity. Attributes are built-in types or other user-defined types. Methods, which are functions or procedures written in PL/SQL and stored in the database, or written in a language like C and stored externally. Methods implement operations the application can perform on the real world entity. An object type is a template. A structured data unit that matches the template is called an object. Purchase Order ExampleHere is an example of how you might define object types called external_person, lineitem and purchase_order. The object types external_person and lineitem have attributes of built-in types. Theobject type purchase_order has a more complex structure, which closely matches the structure of real purchase orders. The attributes of purchase_order are id, contact, and lineitems. The attribute contact is an object, and the attribute lineitems is a nested table. Nested tables are discussed later in this chapter (see "Nested Tables" on page 10-11). CREATE TYPE external_person AS OBJECT ( name VARCHAR2(30), phone VARCHAR2(20) ) ; CREATE TYPE lineitem AS OBJECT (item_name VARCHAR2(30), quantity NUMBER,unit_price NUMBER(12,2) ) ;CREATE TYPE lineitem_table AS TABLE OF lineitem ;CREATE TYPE purchase_order AS OBJECT (id NUMBER, contact external_person, lineitems lineitem_table, MEMBER FUNCTION

Page 84

Page 85: Oracle Questions

Oracle_Questions get_value RETURN NUMBER ) ;This is a simplified example. It does not show how to specify the body of the methodget_value. Nor does it show the fullcomplexity of a real purchase order. See Oracle8Server Application Developer's Guide for a complete purchase orderexample. An object type is a template. Defining it doesn't result in storage allocation. You can use lineitem, external_person, or purchase_order in SQL statements in most of the same places you can use types like NUMBER or VARCHAR2. For example, you might define a relational table to keep track of your contacts: CREATE TABLE contacts ( contact external_person date DATE ) ;

The contact table is a relational table with an object type defining one of its columns. Objects that occupy columns of relational tables are called column objects (see "Row Objects and Column Objects" on page 10-8). MethodsIn the example, purchase_order has a method named get_value. Each purchase order object has its own get_value method.For example, if x and y are PL/SQL variables that hold purchase order objects and w and z are variables that hold numbers,the following two statements can leave w and z with different values: w = x.get_value() ;z = y.get_value() ;After those statements, w has the value of the purchase order referred to by variable x; z has the value of the purchase order referred to by variable y. The term x.get_value () is an invocation of the method get_value. Method definitionscan include parameters, but get_value does not need them, because it finds all of its arguments among the attributes of the object to which its invocation is tied. Thatis, in the first of the sample statements, it computes its value using the attributes of purchase order x. In the second it computes its value using the attributes of purchase order y. This is called the selfish style of method invocation. Every object type also has one implicitly defined method that is not tied to specific objects, the object type's constructor method. Object Type Constructor Methods Every object type has a system-defined constructor method, that is, a method that makes a new object according to the object type's specification. The name of the constructor method is the name of the object type. Its parameters have the name sand types of the object type's attributes. The constructor method is a function. It returns the new object as its value. For example, the expression purchase_order( 1000376, external_person ("John Smith","1-800-555-1212"), NULL )represents a purchase order object with the following attributes: id 1000376 contact external_person("John Smith","1-800-555-1212")lineitems NULLThe expression external_person ("John Smith", "1-800-555-1212") is an invocation of the constructor function for the object type external_person. The object that it returns becomes the contact attribute of the purchase order. See "Nulls" on page 11-6 for a discussion of null objects and null attributes. Comparison MethodsMethods play a role in comparing objects. Oracle has facilities for comparing two data items of a given built-in type (for example, two numbers), and determining whether one is greater than, equal to, or less than the other. Oracle cannot, however,compare two items of an arbitrary user-defined type without further guidancefrom the definer. Oracle provides two ways to define an order relationship among objects of a given object type: map methods and order methods. Map methods use Oracle's ability to compare built-in types. Suppose, for example, that you have defined an object type called rectangle, with attributes height and width. You can define a map method area that returns a number, namely the product ofthe rectangle's height and width attributes. Oracle can then compare two rectangles by comparing their areas.

Order methods are more general. An order method uses its own internal logic to compare two objects of a given object type. It returns a value that encodes the order relationship. For example, it may return -1 if the first is smaller, 0 if theyare equal, and 1

Page 85

Page 86: Oracle Questions

Oracle_Questionsif the first is larger. Suppose, for example, that you have defined an object type called address, with attributes street, city, state, and zip. The terms "greater than" and "less than" may have no meaning for addresses in your application, but you may need to perform complex computations to determine when two addresses are equal. In defining an object type, you can specify either a map method or an order method for it, but not both. If an object type has nocomparison method, Oracle cannot determine a greater than or less than relationship between two objects of that type. It can,however, attempt to determine whether two objects of the type are equal. Oracle compares two objects of a type that lacks a comparison method by comparing corresponding attributes: If all the attributes are non-null and equal, Oracle reports that the objects are equal. If there is an attribute for which the two objects have unequal non-null values, Oracle reports them unequal. Otherwise, Oracle reports that the comparison is not available (null). Object TablesAn object table is a special kind of table that holds objects and provides a relational view of the attributes of those objects. For example, the following statement defines an object table for objects of the external_person type defined earlier: CREATE TABLE external_person_t OF external_person ;Oracle allows you to view this table in two ways: A single column table in which each entry is an external_person object. A multi-column table in which each of the attributes of the object type external_person, namely name and phone, occupies a column. For example, you can execute the following instructions: INSERT INTO external_person_t VALUES ( "John Smith", "1-800-555-1212" ) ;SELECT VALUE(p) FROM external_person_t p WHERE p.name = "John Smith" ;The first instruction inserts a purchase order object into external_person_t as a multi-column table. The second selects from external_person_t as a single column table. Row Objects and Column ObjectsObjects that appear in object tables are called row objects. Objects that appear only in table columns or as attributes of other objects are called column objects. REFsIn the relational model, foreign keys express many-to-one relationships. Oracle withthe objects option provides a more efficient means of expressing many-to-one relationships when the "one" side of the relationship is a row object. Oracle givesevery row object a unique, immutable identifier, called an object identifier. Oracleprovides no documentation of or access to the internal structure of object identifiers. This structure can change at any time. An object identifier allows the corresponding row object to be referred to from other objects or from relational tables. A built-in datatype called REF represents such references. A REF encapsulates a reference to a row object of a specified objecttype. An object view (see Chapter 12, "Object Views") is a virtual object table. Its rows are row objects. Oracle materializes object identifiers, which it does not store persistently, from primary keys in the underlying table or view. Oracle uses these identifiers toconstruct REFs to the row objects in the object view. You can use a REF to examine or update the object it refers to. You can also use a REF to obtain a copy of the object it refers to. The only changes you can make to a REF are to replace its contents with a reference to a different object of the same object type or to assign it a null value. Scoped REFsIn declaring a column type, collection element, or object type attribute to be a REF, you can constrain it to contain only references to a specified object table.

Page 86

Page 87: Oracle Questions

Oracle_QuestionsSuch a REF is called a scoped REF. Scoped REFs require less storage space and allow more efficient access than unscoped REFs. Dangling REFsIt is possible for the object identified by a REF to become unavailable-through either deletion of the object or a change in privileges. Such a REF is called dangling. Oracle SQL provides a predicate (called IS DANGLING) to allow testing REFsfor this condition. Dereferencing REFsAccessing the object referred to by a REF is called dereferencing the REF. Oracle provides the DEREF operator to do this. Dereferencing a dangling REF results in a null object. Oracle provides implicit dereferencing of REFs. For example, consider the following:

CREATE TYPE person AS OBJECT (name VARCHAR2(30), manager REF person ) If x represents an object of type person, then the expression x.manager.namerepresents a string containing the name attribute of the person object referred to by the manager attribute of x. The above expression is a shortened form of: y.name, where y = DEREF(x.manager)Obtaining REFsYou can obtain a REF to a row object by selecting the object from its object table and applying the REF operator. For example, you can obtain a REF to the purchase order with identification number 1000376 as follows: DECLARE OrderRef REF to purchase_order;SELECT REF(po) INTO OrderRef FROM purchase_order_table po WHERE po.id = 1000376 ;collection Types The collection types are array types and table types. Each describes a data unit made up of an indefinite number of elements, all of the same datatype. Array types and table types are schema objects. The corresponding data units are called VARRAYsand nested tables. When there is no danger of confusion, we often avoid circumlocution by referring to the collection types as VARRAYs and nested tables. Collection types have constructor methods. The name of the constructor method is thename of the type, and its argument is a comma-separated list of the new collection'selements. The constructor method is a function. It returns the new collection as itsvalue. An expression consisting of the type name followed by empty parentheses represents acall to the constructor method to create an empty collection of that type. An empty collection is different from a null. VARRAYsAn array is an ordered set of data elements. All elements of a given array are of the same datatype. Each element has an index, which is a number corresponding to theelement's position in the array. The number of elements in an array is the size of the array. Oracle allows arrays tobe of variable size, which is why they are called VARRAYs. You must specify a maximum size when you declare the array type. For example, the following statement declares an array type: CREATE TYPE prices AS VARRAY(10) OF NUMBER(12,2)VARRAYs of type prices have no more than ten elements, each of datatype NUMBER(12,2). Creating an array type does not allocate space. It defines a datatype, which you canuse as The datatype of a column of a relational table. An object type attribute A PL/SQL variable, parameter, or function return type. A VARRAY is normally stored in line, that is, in the same tablespace as the other data in its row. If it is sufficiently large,however, Oracle stores it as a BLOB (see "Import/Export" on page 11-15). For more information on using VARRAYs, see Oracle8 Server Application Developer's Guide. Nested TablesIn the Oracle object-relational database, you can create a table with a column whosedatatype is another table. That is, tables can be nested within other tables as values in a column. The Oracle Server stores nested table data "out of line" from

Page 87

Page 88: Oracle Questions

Oracle_Questionsthe rowsof the parent table, using a store table which is associated with the nested table column. The parent row contains a unique set identifier value associated with a nested table instance.A nested table is an unordered set of data elements, all of the same datatype. It has a single column, and the type of that column is a built-in type or an object type. If an object type, the table can also be viewed as a multi-column table, with a column for each attribute of the object type. For example, in the purchase order example, the following statement declares the table type used for the nested tables of line items: CREATE TYPE lineitem_table AS TABLE OF lineitem ;A table type definition does not allocate space. It defines a type, which you can use as The datatype of a column of a relational table. An object type attribute. A PL/SQL variable, parameter, or function return type.

When a table type appears as the type of a column in a relational table or as an attribute of the underlying object type of an object table, Oracle stores all of thenested table data in a single table, which it associates with the enclosing relational or objecttable (see "Import/Export" on page 11-15). For example, the following statement defines an object table for the object type purchase_order: CREATE TABLE purchase_order_table OF purchase_order NESTED TABLE lineitems STORE AS lineitems_table ;The second line specifies lineitems_table as the storage table for the lineitems attributes of all of the purchase_order objects in purchase_order_table. OTT The Oracle type translator (OTT) is a program that automatically generates C language structure declarations corresponding toobject types. OTT facilitates using the Pro*C precompiler and the OCI server access package. Oracle Database Assistant A wizard that helps you create a database. When you install Oracle8, Oracle Installer detects if there is a database on your system. If not, you may choose to use this wizard at the end of the installation process to create a database.

Application developers frequently ask how they can access 3GL routines (such as C orC++ functions) or operating system services from PL/SQL code that is running on a server. One way to do this is to use the Oracle-supplied DBMS_PIPES package.

--This section deals with object views in oracle 8 This example is based on a simple business activity: managing the data in customer orders. The example is in three parts. Thefirst two are in this chapter. The third is in Chapter 8, "Object Views-An Extended Example".

Each part implements a database to support the basic activity. The first part implements the database using only Oracle's built-in datatypes. This is called the relational approach. It creates tables to hold the application's data and uses well-known techniques to implement the application's entity relationships.

The second and third parts use user-defined types to translate the entities and relationships directly into database terms. This is called the object-relational approach. The second and third parts use identical user-defined types. They differ only in the waythey implement the underlying data storage. The second part of the example creates object tables to hold the underlying data. Ituses these instead of the tables created in the first part. The third part uses the relational tables created in the first part. Rather than building object tables, it uses object views to materialize virtual object tables. The basic entities in this example are Customers ,The stock of products for sale Purchase orders

Page 88

Page 89: Oracle Questions

Oracle_QuestionsPurchase orders have an n : 1 relationship with customers, because a customer can place many orders, but a given purchase order is from a single customer. Purchase orders have an m : n relationship with the stock. A purchase order can contain many stock items, and a stock item can appear on many purchase orders. The usual way to manage the m : n relationship between purchase orders and stock is to introduce another entity called a line item list. A purchase order can have an arbitrary number of line items, but each line item belongs to a single purchase order. A stock item can appear on many line items, but each line item refers to a single stock item. Table 7-1 lists the information about each of these entities that an application to manage customer orders needs. Table 7-1: Information Required about Entities in the Purchase Order Example Entity Required Information Customer Contact information Stock Item identification, cost, and taxability code Purchase Order Customer, order and ship dates, shipping address Line Item List Stock item, quantity, price (discount), for each line item At this point the attributes describing the entities are complex. Built-in types cannot represent them directly. An address contains attributes like street, city, state, and zipcode. A customer may have several phone numbers. The line item list isan entity in its own right and also an attribute of a purchase order. The relationaland object-relational approaches map this rich structure in different ways. Part 1: Relational ApproachThe relational approach normalizes entities and their attributes. It puts the customer, purchase order, and stock entities into tables. It breaks addresses into their standard components. It sets an arbitrary limit on the number of telephone numbers acustomer can have and assigns a column to each. The relational approach separates line items from their purchase orders and puts them into a table of their own. The table has columns for foreign keys to the stock and purchase order tables. Tables The relational approach results in the following tables: CREATE TABLE customer_info (custno NUMBER, custname VARCHAR2(200), street VARCHAR2(200), city VARCHAR2(200), state CHAR(2), zip VARCHAR2(20), phone1 VARCHAR2(20), phone2 VARCHAR2(20), phone3 VARCHAR2(20), PRIMARY KEY (custno) ) ;CREATE TABLE purchase_order (pono NUMBER,custno NUMBER REFERENCES customer_info, orderdate DATE, shiptodate DATE, shiptostreet VARCHAR2(200), shiptocity VARCHAR2(200), shiptostate CHAR(2), shiptozip VARCHAR2(20), PRIMARY KEY (pono) ) ;CREATE TABLE stock_info (stockno NUMBER PRIMARY KEY,cost NUMBER, tax_code NUMBER) ;CREATE TABLE line_items (lineitemno NUMBER, pono NUMBER REFERENCES purchase_order,stockno NUMBER REFERENCES stock_info, quantity NUMBER,discount NUMBER, PRIMARY KEY (pono, lineitemno) ) no to the purchase_order table and stockno to the stock_info table.

Inserting Values

In an application based on the tables defined in the previous section, statements like the following insert data into the tables:

INSERT INTO customer_info VALUES (1, 'Jean Nance', '2 Avocet Drive', 'Redwood Shores', 'CA', '95054', `415-555-1212', NULL, NULL) ;INSERT INTO customer_info VALUES (2, 'John Nike', '323 College Drive', 'Edison', 'NJ', '08820',`609-555-1212', `201-555-1212', NULL) ;

INSERT INTO purchase_order VALUES (1001, 1, SYSDATE, '10-MAY-1997',Page 89

Page 90: Oracle Questions

Oracle_Questions NULL, NULL, NULL, NULL) ;INSERT INTO purchase_order VALUES (2001, 2, SYSDATE, '20-MAY-1997', '55 Madison Ave', 'Madison', 'WI', `53715') ;INSERT INTO stock_info VALUES(1004, 6750.00, 2) ;INSERT INTO stock_info VALUES(1011, 4500.23, 2) ;INSERT INTO stock_info VALUES(1534, 2234.00, 2) ;INSERT INTO stock_info VALUES(1535, 3456.23, 2) ;INSERT INTO line_items VALUES(01, 1001, 1534, 12, 0) ;INSERT INTO line_items VALUES(02, 1001, 1535, 10, 10) ;INSERT INTO line_items VALUES(10, 2001, 1004, 1, 0) ;INSERT INTO line_items VALUES(11, 2001, 1011, 2, 1) ;

SelectingIn an application based on the tables defined earlier, queries like the following provide necessary information from the stored data. Customer and Line Item Data for Purchase Order 1001SELECT C.custno, C.custname, C.street, C.city, C.state, C.zip, C.phone1, C.phone2, C.phone3, P.pono, P.orderdate, L.stockno, L.lineitemno, L.quantity, L.discount FROM customer_info C, purchase_order P, line_items L WHERE C.custno = P.custno AND P.pono = L.pono AND P.pono = 1001;Total Value of Each Purchase OrderSELECT P.pono, SUM(S.cost * L.quantity) FROM purchase_order P, line_items L,stock_info S WHERE P.pono = L.pono AND L.stockno = S.stockno GROUP BY P.pono;Purchase Order and Line Item Data Involving Stock Item 1004SELECT P.pono, P.custno,L.stockno, L.lineitemno, L.quantity, L.discount FROM purchase_order P, line_items L WHERE P.pono = L.pono (+) AND L.stockno = 1004;UpdatingIn an application based on the tables defined earlier, statements like the followingupdate the stored data: Update the Quantity for Purchase Order 01 and Stock Item 1001 UPDATE line_items SET quantity = 20 WHERE pono = 1 AND stockno = 1001 ;DeletingIn an application based on the tables defined earlier, statements like the followingdelete stored data: Delete Purchase Order 1001 DELETE FROM line_items WHERE pono = 1001 ;DELETE FROM purchase_order WHERE pono = 1001 ;Part 2: Object-Relational Approach with Object TablesThe object-relational approach begins with the entity relationships outlined in "Entities and Relationships" on page 7-3. User-defined types make it possible to carry more of that structure into the schema. Rather than breaking up addresses or the customer's contact phones into unrelated columns in relational tables, the object-relational approach defines types to represent them. Rather than breaking line items out into a separate table, the object-relational approach allows them to stay with their respective purchase ordersas nested tables. In the object-relational approach, the main entities-customers, stock, and purchase orders-become objects. Object references express the n : 1 relationships between them. Collection types model their multi-valued attributes. Given an object-relational schema, there are two approaches to implementing it: create and populate object tables or use object views to materialize virtual object tables out of existing relational data. The remainder of this chapter develops the object-relational schema and shows how toimplement it with object tables. Chapter 8, "Object Views-An Extended Example" implements the same schema with object views.

Defining TypesThe following statements set the stage: CREATE TYPE line_item_t ;CREATE TYPE purchase_order_t ;

Page 90

Page 91: Oracle Questions

Oracle_QuestionsCREATE TYPE stock_info_t ;

The preceding three statements define incomplete object types. The incomplete definitions notify Oracle that full definitions are coming later. Oracle allows types that refer to these types to compile successfully. Incomplete type declarations are likeforward declarations in C and other programming languages.

The next statement defines an array type. CREATE TYPE phone_list_t AS VARRAY(10) OF VARCHAR2(20) ;The preceding statement defines the type phone_list_t. Any data unit of type phone_list_t is a VARRAY of up to 10 telephone numbers, each represented by a data item of type VARCHAR2. A list of phone numbers could occupy a VARRAY or a nested table. In this case, the list is the set of contact phone numbers for a single customer. A VARRAY is a betterchoice than a nested table for the following reasons: The order of the numbers might be important. VARRAYs are ordered. Nested tablesare unordered. The number of phone numbers for a specific customer is small. VARRAYsforce you to specify a maximum number of elements (10 in this case) in advance. Theyuse storage more efficiently than nested tables, which have no special size limitations. There is no reason to query the phone number list, so the table format offers no benefit.In general, if ordering and bounds are not important designconsiderations, designers can use the following rule of thumb for deciding between VARRAYs and nested tables: If you need to query the collection, use nested tables; if you intend to retrieve the collection as a whole, use VARRAYs. The next statementdefines an object type. CREATE TYPE address_t AS OBJECT (street VARCHAR2(200), city VARCHAR2(200), state CHAR(2), zipVARCHAR2(20) ) ;The preceding statement defines the object type address_t. Data units of this type represent addresses. All of their attributes are character strings, representing theusual parts of a slightly simplified mailing address. The next statement defines an object type that uses other user-defined types as building blocks. The object type also has a comparison method. CREATE TYPE customer_info_t AS OBJECT (custno NUMBER,custname VARCHAR2(200), address address_t, phone_list phone_list_t, ORDER MEMBER FUNCTIONcust_order(x IN customer_info_t) RETURN INTEGER, PRAGMA RESTRICT_REFERENCES (cust_order, WNDS, WNPS, NPS, RNDS) ) ;The preceding statement defines the object type customer_info_t. Data units of that type are objects that represent blocks of information about specific customers. The attributes of a customer_info_t object are a number, a character string, anaddress_tobject, and a VARRAY of type phone_list_t.

Every customer_info_t object also has an associated order method, one of the two types of comparison methods. Whenever Oracle needs to compare two customer_info_t objects, it invokes the cust_order method to do so. The two types of comparison methods are map methods and order methods. See Oracle8 Server Concepts for a discussion of order and map methods and how to choose the right one for a given application. This application uses one of each to for purposesof illustration. The pragma declaration provides information to PL/SQL about what sort of access the method needs to the database. See PL/SQL User's Guide and Reference for details of how to use pragma declarations. The statement does not include the actual PL/SQL program implementing the method cust_order. That appears in a later section. The next statement completes the definition of the incomplete object type line_item_t declared at the beginning of this section. CREATE TYPE line_item_t AS OBJECT (lineitemno NUMBER, stockref REF stock_info_t,quantity NUMBER,discount NUMBER ) ;

The preceding statement defines the object type line_item_t. Data units of that typeare objects that represent line items. They have three numeric attributes and one REF attribute. The next statement creates a table type. CREATE TYPE line_item_list_t AS TABLE OF line_item_t ;

Page 91

Page 92: Oracle Questions

Oracle_QuestionsThe preceding statement defines the table type line_item_list_t. A data unit of thattype is a nested table, each row of which contains a line_item_t object. A nested table of line items is better choice to represent the multivalued line item list of a purchase order than a VARRAY of line_item_t objects would be, for the following reasons: Querying the contents of line items is likely to be a requirement for most applications. This is an inefficient operation for VARRAYs, since it involves casting the VARRAY to a nested table first. Indexing on line item data may be a requirement in some applications. Nested tables allow this, but it is not possible with VARRAYs. The order of line items is usually unimportant, and the line item number can beused to specify an order when necessary. There is no practical upper bound on the number of line items on a purchase order. Using a VARRAY requires specifying an upper bound on the number of elements. The following statement completes the definition of the incomplete object type purchase_order_t declared at the beginning of this section. CREATE TYPE purchase_order_t AS OBJECT (pono NUMBER, custref REF customer_info_t,orderdate DATE, shipdate DATE,line_item_list line_item_list_t,shiptoaddr address_t, MAP MEMBER FUNCTION ret_value RETURN NUMBER, PRAGMA RESTRICT_REFERENCES (ret_value, WNDS, WNPS, RNPS, RNDS), MEMBER FUNCTION total_value RETURN NUMBER, PRAGMA RESTRICT_REFERENCES (total_value, WNDS, WNPS)) ;

The preceding statement defines the object type purchase_order_t. Data units of thistype are objects representing purchase orders. They have six attributes, including aREF, a nested table of type line_item_list_t, and an address_t object. Objects of type purchase_order_t have two methods: ret_value and total_value. One isa map method, one of the two kinds of comparison methods. Whenever Oracle needs to compare two purchase_order_t objects, it implicitly calls the ret_value method to doso. The two pragma declarations provide information to PL/SQL about what sort of access the two methods need to the database.See PL/SQL User's Guide and Reference for complete details of how to use pragma declarations. The statement does not include the actual PL/SQL programs implementing the methods ret_value and total_value. That appearsin a later section. The next statement completes the definition of stock_info_t, the last of the three incomplete object types declared at the beginning of this section. CREATE TYPE stock_info_t AS OBJECT (stockno NUMBER, cost NUMBER, tax_code NUMBER ) ;The preceding statement defines the object type stock_info_t. Data units of this type are objects representing the stock items that customers order. They have three numeric attributes. Method definitionsThis section shows how to specify the methods of the customer_info_t and purchase_order_t object types. The following statement defines the methods of the purchase_order_t object type. CREATE OR REPLACE TYPE BODY purchase_order_t AS MEMBER FUNCTION total_value RETURN NUMBER IS i INTEGER; stock stock_info_t; line_item line_item_t; total NUMBER := 0; cost NUMBER; BEGIN FOR i IN 1..SELF.line_item_list.COUNT LOOP line_item := SELF.line_item_list(i); SELECT DEREF(line_item.stockref) INTO stock FROM DUAL ;

total := total + line_item.quantity * stock.cost ;

END LOOP;Page 92

Page 93: Oracle Questions

Oracle_Questions RETURN total; END;

MAP MEMBER FUNCTION ret_value RETURN NUMBER IS BEGIN RETURN pono; END;END;

The total_value method illustrates a number of important concepts and needs further explanation. The ret_value method, on the other hand is simple. It merely returns the number of its associated purchase_order_t object. Since ret_value is a map method,Oracle uses the value it returns, namely the purchase order number, as the basis forcomparing purchase_order_t objects.

The preceding statement defines the body of the purchase_order_t object type, that is, the PL/SQL programs that implement its methods. The basic function of the total_value method is to return the sum of the extended values of the line items of its associated purchase_order_t object. The keyword SELFrefers to that object.

The keyword COUNT is the name of a system-generated attribute of every collection type. It contains the number of elements in the collection. The term SELF.line_item_list.COUNT represents the number of elements in the nested table thatis the line_item_list attribute of the purchase_order_t object represented by SELF. The term DEREF (line_item.stockref) represents the stock_info_t object referred to by the stockref attribute of the line_item_t object that is the i-th element of the nested table that is the line_item_list attribute of the purchase_order_t object represented by SELF. The SQL SELECT statement with the explicit DEREF call is required, because Oracle does not support implicit dereferencing of REFs within PL/SQL programs.

The PL/SQL variable stock is of type stock_info_t. The select statement sets it to the object represented by DEREF (line_item.stockref). That object is the stock item referred to in the i-th line item, so the program refers to the stock item's cost asstock.cost, the cost attribute of the stock_info_t object that stock refers to. The other term needed to compute the extended cost of the i-th line item is the quantity associated with that line:line_item.quantity. This term represents the quantity attribute of the line_item_t object that is the i-th element of the nested table that is the line_item_list attribute of the purchase_order_t object represented by SELF. The remainder of the method program is straightforward. The loop sums the extended values of the line items, and the method returns the total as its value. The following statement defines the cust_order method of the customer_info_t object type.

CREATE OR REPLACE TYPE BODY customer_info_t AS ORDER MEMBER FUNCTION cust_order (x IN customer_info_t) RETURN INTEGER IS BEGIN RETURN custno - x.custno; END;END;The order method cust_order accepts another customer_info_t object as an input argument and returns the difference of the two custno attributes. Since it subtractsthe custno of the other customer_info_t object from its own object's custno, themethod returns a negative number if its own object has a smaller value of custno, a positive number if its own has a larger value of custno, and zero if the two objectshave the same value of custno. This completes the definition of the user-defined types used in the purchase order application. None of the declarations create tables or reserve data storage space.

Page 93

Page 94: Oracle Questions

Oracle_QuestionsCreating Object Tables To this point the example is the same, whether you plan to create and populate object tables or implement the application with object views on top of the relational tables that appear in the first part of the example. The remainder of this chapter continues the example using object tables. Chapter 8, "Object Views-An Extended Example" picks up from this point and continues the example with object views.

The following sta********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************The statement defines a primary key constraint on the custno column. This constraintapplies only to this table, not to all customer_info_t objects. Another object tableof customer_info_t objects need not satisfy that constraint. This illustrates an important point: Constraints apply to tables, not to type definitions. The address column contains address_t objects. These have attributes of built-in types. They are leaf-level scalar attributes of customer_info_t, so Oracle creates columns for them in the object table customer_tab. You can refer to these columns usingthe dot notation. For example, if you wish to build an index on the zip column, you can refer to it as address.zip. The phone_list column contains VARRAYs of type phone_list_t. VARRAYs of type phone_list_t contain no more than 200 characters of phone numbers, plus a small amount of overhead. As a result, Oracle stores the VARRAY as a single data unit inthe phone_list column. Oracle stores VARRAYs that exceed 4000 bytes in BLOBs. The next statement creates an object table for stock_info_t objects. CREATE TABLE stock_tab OF stock_info_t (stockno PRIMARY KEY) ;The preceding statement creates the stock_tab object table. Each row of the table isa stock_info_t object. Each such object has three numeric attributes. Oracle assignsa column to each. The statement places a primary key constraint on the stocknocolumn. The next statement defines an object table for purchase_order_t objects. CREATE TABLE purchase_tab OF purchase_order_t (PRIMARY KEY (pono), SCOPE FOR (custref) IS customer_tab ) NESTED TABLE line_item_list STORE AS po_line_tab ;

The preceding statement creates the purchase_tab object table. Each row of the tableis a purchase_order_t object.Attributes of purchase_order_t objects are: pono NUMBER custref REF customer_info_t orderdate DATE shipdate DATE line_item_list line_item_list_t shiptoaddr address_tEach row has a nested table column line_item_list. The last line of the statement creates the table po_line_tab to hold the line_item_list columns of all of the rows of the purchase_tab table. The statement places a primary key constraint on the pono column. The statement places a scope on the REFs in the custref column. These REFs can referonly to row objects in the customer_tab object table. The scope limitation applies only to custref columns of the customer_tab object table. It does not apply to the custref attributes of purchase_order_t objects that are not stored in the customer_tab object table. Oracle creates columns in customer_tab for the remaining leaf level scalar attributes of purchase_order_t objects, namely, orderdate, shipdate, and the attributes of the address_t object in shiptoaddr. At this point all of the tables for the purchase order application are in place. Thenext section shows how to add additional specifications to these tables. Altering the TablesThe next statement alters the po_line_tab storage table, which holds the

Page 94

Page 95: Oracle Questions

Oracle_Questionsline_item_list nested table columns of the object table purchase_tab, to place a scope on the REFs it contains.

ALTER TABLE po_line_tab ADD (SCOPE FOR (stockref) IS stock_tab) ;The po_line_tab storage table holds nested table columns of type line_item_list_t. The definition of that type (from earlier in the chapter) is: CREATE TYPE line_item_list_t AS TABLE OF line_item_t ;An attribute of a line_item_t object, and hence one column of the po_line_tab storage table, is stockref, which is of type REF stock_info_t. The object table stock_tab holds row objects of type stock_info_t. The alter statement restricts the scope of the REFs in the stockref column to the object table stock_tab. A nested table whose elements are not of an object type has a single unnamed column.Oracle recognizes the keyword COLUMN_VALUE as representing the name of that column. The keyword COLUMN_VALUE makes it possible to place a scope on the elements of a nested table of REFs. The next statement further alters the po_line_tab storage table to specify its indexstorage. ALTER TABLE po_line_tab STORAGE (NEXT 5K PCTINCREASE 5 MINEXTENTS 1 MAXEXTENTS 20) ;The next statement creates an index on the po_line_tab storage table. CREATE INDEX po_nested_in ON po_line_tab (NESTED_TABLE_ID) ;A storage table for a nested table column of an object table has a hidden column called NESTED_TABLE_ID. The preceding statement creates an index on that column, making access to the contents of line_item_list columns of the purchase_tab object table more efficient.

All elements of the nested table in a column of a given row of purchase_tab have thesame value of NESTED_TABLE_ID.Elements of the same column in a different row of purchase_tab have a different value of NESTED_TABLE_ID. The next statement shows how to use NESTED_TABLE_ID to enforce uniqueness of a column of a nested table within each row of the enclosing table. It creates a uniqueindex on the po_line_tab storage table. That table holds the line_item_list columns of all of the rows of the purchase_tab table. CREATE UNIQUE INDEX po_nested ON po_line_tab (NESTED_TABLE_ID, lineitemno) ;By including the lineitemno column in the index key and specifying a unique index, the statement ensures that the lineitemno column contains distinct values within each purchase order. Inserting ValuesThe statements in this section show how to insert the same data into the object tables just created as the statements on page 7-5 insert into the relational tables of the first part of the example. stock_tabINSERT INTO stock_tab VALUES(1004, 6750.00, 2);INSERT INTO stock_tab VALUES(1011, 4500.23, 2);INSERT INTO stock_tab VALUES(1534, 2234.00, 2);INSERT INTO stock_tab VALUES(1535, 3456.23, 2);customer_tabINSERT INTO customer_tab VALUES (1, `Jean Nance',address_t(`2 Avocet Drive', `Redwood Shores', `CA', `95054'),phone_list_t(`415-555-1212')) ;INSERT INTO customer_tab VALUES ( 2, `John Nike', address_t(`323 College Drive', `Edison', `NJ', `08820'), phone_list_t(`609-555-1212',`201-555-1212')) ;purchase_tabINSERT INTO purchase_tab SELECT 1001, REF(C), SYSDATE,'10-MAY-1997',line_item_list_t(), NULL FROM customer_tab C WHERE C.custno = 1 ;The preceding statement constructs a purchase_order_t object with the following attributes: pono 1001

Page 95

Page 96: Oracle Questions

Oracle_Questions custref REF to customer number 1 orderdate SYSDATE shipdate 10-MAY-1997 line_item_list an empty line_item_list_t shiptoaddr NULLThe statement uses a query to construct a REF to the row object in the customer_tab object table that has a custno value of1.

The next statement uses a flattened subquery, signaled by the keyword THE, to identify the target of the insertion, namely the nested table in the line_item_list column of the row object in the purchase_tab object table that has a pono value of 1001. INSERT INTO THE (SELECT P.line_item_list FROM purchase_tab P WHERE P.pono = 1001 ) SELECT 01, REF(S), 12, 0 FROM stock_tab S WHERE S.stockno = 1534;The preceding statement inserts a line item into the nested table identified by the flattened subquery. The line item that it inserts contains a REF to the row object in the object table stock_tab that has a stockno value of 1534. The following statements are similar to the preceding two. INSERT INTO purchase_tab SELECT 2001, REF(C), SYSDATE,'20-MAY-1997',line_item_list_t(), address_t(`55 Madison Ave','Madison','WI','53715') FROM customer_tab C WHERE C.custno = 2;INSERT INTO THE ( SELECT P.line_item_list FROM purchase_tab P WHERE P.pono = 1001 ) SELECT 02, REF(S), 10, 10 FROM stock_tab S WHERE S.stockno = 1535;INSERT INTO THE ( SELECT P.line_item_list FROM purchase_tab P WHERE P.pono = 2001 ) SELECT 10, REF(S), 1, 0 FROM stock_tab S WHERE S.stockno = 1004;

INSERT INTO THE (SELECT P.line_item_list FROM purchase_tab P WHERE P.pono = 2001 ) VALUES( line_item_t(11, NULL, 2, 1) ) ;The next statement uses a table alias to refer to the result of the flattened subquery UPDATE THE ( SELECT P.line_item_list FROM purchase_tab P WHERE P.pono = 2001 ) plist SET plist.stockref =(SELECT REF(S)FROM stock_tab S WHERE S.stockno = 1011) WHERE plist.lineitemno = 11 ;Selecting The following query statement implicitly invokes a comparison method. It shows how Oracle uses the ordering of purchase_order_t object types that the comparison method defines. SELECT p.pono FROM purchase_tab p ORDER BY VALUE(p);The preceding instruction causes Oracle to invoke the map method ret_value for each purchase_order_t object in the selection. Since that method simply returns the valueof the object's pono attribute, the result of the selection is a list of purchase order numbers in ascending numerical order. The following queries correspond to the queries in "Selecting" on page 7-5. Customer and Line Item Data for Purchase Order 1001SELECT DEREF(p.custref), p.shiptoaddr, p.pono, p.orderdate, line_item_list FROM purchase_tab p WHERE p.pono = 1001 ;Total Value of Each Purchase OrderSELECT p.pono, p.total_value() FROM purchase_tab p ;Purchase Order and Line Item Data Involving Stock Item 1004

SELECT po.pono, po.custref.custno,CURSOR (SELECT *FROM TABLE (po.line_item_list) L WHERE L.stockref.stockno = 1004 ) FROM purchase_tab po ; DeletingThe following example has the same effect as the two deletions needed in the relational case (see "Deleting" on page 7-7). In this case Oracle automatically

Page 96

Page 97: Oracle Questions

Oracle_Questionsdeletes all line items belonging to the deleted purchase order. The relational case needs a separate step. Delete Purchase Order 1001DELETE FROM purchase_order WHERE pono = 1001 ;This concludes the object table version of the purchase order example. The next chapter develops an alternative version of the example using relational tables and object views.Purchase Order ExampleChapter 7, "User-Defined Datatypes -An Extended Example" develops a purchase order example by following these steps: 1.Establish the entities and relationships. 2.Implement the entity-relationship structure by creating and populating relational Tables. 3.Define an object-relational schema of user-defined types to model the entity-relationship structure. 4.Implement the entity-relationship structure using the object-relational schema to create and populate object tables. The approach in this chapter uses the same initial steps but a different final step.Rather than creating and populating object tables, this approach uses object views to materialize virtual object tables out of data in the relational tables. Defining Object ViewsThe example developed in Chapter 7 contains three object tables: customer_tab, stock_tab, and purchase_tab. This chapter contains three corresponding object views:customer_view, stock_view, and purchase_view. The statement that creates an object view has four parts: The name of the view. The name of the object type it is based on. The source of the primary-key-based object identifier. A selection that populates the virtual object table corresponding to the object type. The customer_view ViewThe definition of the customer_info_t object type appears on page 7-9. This object view is based on that object type. CREATE OR REPLACE VIEWcustomer_view OF customer_info_t WITH OBJECT OID(custno) AS SELECT C.custno, C.custname, address_t(C.street, C.city, C.state, C.zip), phone_list_t (C.phone1, C.phone2, C.phone3) FROM customer_info C ;This object view selects its data from the customer_info table. The definition of this table appears on page 7-4. The customer_info_t object type has the following attributes: custno NUMBER custname VARCHAR2(200)address address_t phone_list phone_list_t The object view definition takes the custno and custname attributes from correspondingly named columns of the customer_info table. It uses the street, city, state, and zip columns of the customer_info table as arguments to the constructor function for the address_t object type, which is defined on page 7-8. The stock_view ViewThe definition of the stock_info_t object type appears on page 7-11. This object view is based on that object type. CREATE OR REPLACE VIEW stock_view OF stock_info_t WITH OBJECT OID(stockno) AS SELECT * FROM stock_info ;This object view selects its data from the stock_info table. The definition of this table appears on page 7-4. The selection used to materialize the object view is extremely simple, because the object type definition and the table definition correspond exactly. The purchase_view ViewThe definition of the purchase_order_t object type appears on page 7-10. This objectview is based on that object type. CREATE OR REPLACE VIEW purchase_view OF purchase_order_t WITH OBJECT OID (pono) AS SELECT P.pono, MAKE_REF (customer_view, P.custno), P.orderdate, P.shiptodate,CAST (MULTISET (SELECT line_item_t ( L.lineitemno,MAKE_REF(stock_view, L.stockno),L.quantity, L.discount ) FROM line_items L WHERE L.pono= P.pono )AS line_item_list_t),

Page 97

Page 98: Oracle Questions

Oracle_Questions address_t (P.shiptostreet, P.shiptocity, P.shiptostate, P.shiptozip) FROM purchase_order P ;This object view is based on the line_items table, which is defined on page 7-4, thepurchase_order table, which is defined on page 7-4, and the customer_view and stock_view object views defined in the two previous sections. The purchase_order_t object type has the following attributes : pono NUMBER custref REF customer_info_t orderdate DATE shipdate DATE line_item_list line_item_list_t shiptoaddr address_tThe object view definition takes its pono column from the pono column of the purchase_order table. It uses the expression MAKE_REF (customer_view, custno) to create a REF to the row object in the customer_view object view identified bycustno. That REF becomes the custref column. The object view definition takes its orderdate and shipdate columns from the orderdate and shiptodate columns of the purchase_order table. The object view definition uses the term CAST ( MULTISET (SELECT line_item_t ( L.lineitemno,MAKE_REF(stock_view, L.stockno), L.quantity, L.discount)FROM line_items L WHERE L.pono= P.pono )AS line_item_list_t), to materialize the line_item_list column of the object view. At the innermost level of this expression, the operatorMAKE_REF(stock_view, stockno) builds a REF to the row object in the stock_view object view identified by stockno. That REF becomes one of the input arguments to ********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************set, making it an appropriate argument for the CAST operator, which turns itinto a nested table of type line_item_list_t, as specified by the AS clause. The resulting nested table becomes the line_item_list column of the object view. Finally, the definition uses the shiptostreet, shiptocity, shiptostate, and shiptozip columns of the purchase_order table as arguments to the constructor function for the address_t object type to materialize the shiptoaddr column of the object view. Updating the Object ViewsOracle provides INSTEAD OF triggers as a way to update complex object views. This section presents the INSTEAD OF triggers necessary to update the object views just defined. Oracle invokes an object view's INSTEAD OF trigger whenever a command directs it to change the value of any attribute of a row object in the view. Oracle makes both thecurrent value and the requested new value of the row object available to thetrigger program. It recognizes the keywords :OLD and :NEW as representing the current and new values. INSTEAD OF Trigger for purchase_viewCREATE OR REPLACE TRIGGERpoview_insert_tr INSTEAD OF INSERT ON purchase_viewDECLARE line_itms line_item_list_t ; i INTEGER ; custvar customer_info_t ; stockvar stock_info_t ; stockvartemp REF stock_info_t ;BEGIN line_itms := :NEW.line_item_list ; SELECT DEREF(:NEW.custref) INTO custvar FROM DUAL ; INSERT INTO purchase_order VALUES ( :NEW.pono, custvar.custno, :NEW.orderdate, :NEW.shipdate, :NEW.shiptoaddr.street, :NEW.shiptoaddr.city,

Page 98

Page 99: Oracle Questions

Oracle_Questions :NEW.shiptoaddr.state, :NEW.shiptoaddr.zip ) ; FOR i IN 1..line_itms.COUNT LOOP stockvartemp := line_itms(i).stockref ; SELECT DEREF(stockvartemp) INTO stockvar FROM DUAL ; INSERT INTO line_items VALUES ( line_itms(i).lineitemno, :NEW.pono, stockvar.stockno, line_itms(i).quantity, line_itms(i).discount ) ; END LOOP ;END ;This trigger program inserts new values into the purchase_order table. Then, in a loop, it inserts new values into the line_items table for each line_item_t object inthe nested table in the new line_item_list column. The use of the stockvartemp variable is an alternative to implicitly dereferencing the REF represented by line_itms(i).stockref. INSTEAD OF Trigger for customer_viewCREATE OR REPLACE TRIGGER custview_insert_tr INSTEAD OF INSERT ON customer_viewDECLARE phones phone_list_t; tphone1 customer_info.phone1%TYPE := NULL; tphone2 customer_info.phone2%TYPE := NULL; tphone3 customer_info.phone3%TYPE := NULL;BEGIN phones := :NEW.phone_list; IF phones.COUNT > 2 THEN tphone3 := phones(3); END IF; IF phones.COUNT > 1 THEN tphone2 := phones(2); END IF; IF phones.COUNT > 0 THEN tphone1 := phones(1); END IF; INSERT INTO customer_info VALUES ( :NEW.custno, :NEW.custname, :NEW.address.street, :NEW.address.city, :NEW.address.state, :NEW.address.zip, tphone1, tphone2, tphone3);END ;This trigger function updates the customer_info table with the new information. Mostof the program deals with updating the three phone number columns of the customer table from the :NEW.phone_list VARRAY of phone numbers. The IF statements assure that the program does not attempt to access :NEW.phone_list elements with indexes greater than :NEW.phone_list.COUNT. There is a slight mismatch between these two representations, because the VARRAY is defined hold up to 10 numbers, while the customer table has only three phone number columns. The trigger program discards :NEW.phone_list elements withindexes greater than 3. INSTEAD OF Trigger for stock_viewCREATE OR REPLACE TRIGGERstockview_insert_tr INSTEAD OF INSERT ON stock_viewBEGIN INSERT INTO stock_info VALUES ( :NEW.stockno, :NEW.cost, :NEW.tax_code );END ;This trigger function updates the stock_info table with the new information. Sample UpdatesThe following statement fires the customer_view trigger. INSERT INTO customer_view VALUES ( 13, `Ellan White',address_t(`25 I Street', `Memphis', `TN', `05456'), phone_list_t(`615-555-1212') );The preceding statement inserts a new cutomer into the database via the customer_view object view. The following statement fires the purchase_view trigger. INSERT INTO purchase_view

Page 99

Page 100: Oracle Questions

Oracle_Questions SELECT 3001, REF(c), SYSDATE, SYSDATE, CAST(MULTISET(SELECT line_item_t(41, REF(S), 20, 1) FROM stock_view S WHERE S.stockno = 1535 ) AS line_item_list_t ),address_t(`22 Nothingame Ave','Cockstown','AZ','44045') FROM customer_view c WHERE c.custno = 1The preceding statement inserts a new purchase order into the database via the purchase_view object view. Customer number1 has ordered 20 of stock item 1535. The statement assigns number 3001 to the purchase order and number 41 to the line item. SelectingThe three queries in "Selecting" on page 7-19 work exactly as written, but with the object table name purchase_tab replaced by the object view name purchase_view. Queries involving other object tables work with the analogous name replacement.

******This section deals with some general topic of Oracle 8.

Object-oriented programming is rapidly gaining acceptance because it can reduce the cost and time required to build complex applications.

The Object-Relational Model for Database Management Database management systems have evolved from hierarchical to network to relational models. The most widely accepted database model is the relational model. Oracle extends the relational model to an object-relational model, which makes it possible to store complex business models in a relational database.The relational model has three major aspects:

Structures Structures are well-defined objects (such as tables, views, indexes, and so on) that store or access the data of a database. Structures and the data contained within them can be manipulated by operations. Operations Operations are clearly defined actions that allow users to manipulate the data and structures of a database. The operations on a database must adhere to apredefined set of integrity rules. Integrity Rules Integrity rules are the laws that govern which operations are allowed on the data and structures of a database. Integrity rules protect the data and the structures of a database.

Relational database management systems offer benefits such as: independence of physical data storage and logical database structure variable and easy access to all data complete flexibility in database design reduced data storage and redundancy

The Object-Relational Model The object-Relational model allows users to define object types, specifying both thestructure of the data and the methods of operating on the data, and to use these datatypes within the relational model. Object types are abstractions of the real-world entities-for example, purchase

Page 100

Page 101: Oracle Questions

Oracle_Questionsorders-that application programs deal with. An object type has three kinds of components: A name, which serves to identify the object type uniquely. Attributes, which are built-in datatypes or other user-defined types. Attributes model the structure of the real world entity. Methods, which are functions or procedures written in PL/SQL and stored in the database, or written in a language like C and stored externally. Methods implement specific operations that an application can perform on the data. Every object type has a constructor method that makes a new object according to the datatype's specification.

The scalability features of Oracle8 such as partitioned tables, LOB datatypes,index-organized tables, and deferred constraint checking as well as the object features such as user-defined views, object tables, and referenced and embedded object types.

****This section deals with Oracle 8 PL/SQL.

PL/SQLIn PL/SQL, object-oriented programming is based on object types. They provide abstract templates forreal-world objects, and so are an ideal modeling tool. They also provide black-box encapsulation like an integrated component that can be plugged into various electronic devices. To plug an object type into your programs, you need to know only what it does, not how it works. It was not possible to call a 3GL routine directly from PL/SQL in release 7.3 of theOracle Server. Object TypesIn PL/SQL, object-oriented programming is based on object types. An object type encapsulates a data structure along with the functions and procedures needed to manipulate the data. The variables that form the data structure are called attributes.The functions and procedures that characterize the behavior of the object type are called methods.

Object types reduce complexity by breaking down a large system into logical entities. This allows you to create software components that are modular, maintainable, and reusable.

When you define an object type using the CREATE TYPE statement (in SQL*Plus for example), you create an abstract template for some real-world object. As the following example of a bank account shows, the template specifies only those attributes and behaviors the object will need in the application environment:

CREATE TYPE Bank_Account AS OBJECT ( acct_number INTEGER(5), balance REAL, status VARCHAR2(10), MEMBER PROCEDURE open (amount IN REAL), MEMBER PROCEDURE validate (num IN INTEGER), MEMBER PROCEDURE close (num IN INTEGER, amount OUT REAL), MEMBER PROCEDURE deposit (num IN INTEGER, amount IN REAL), MEMBER PROCEDURE withdraw (num IN INTEGER, amount IN REAL), MEMBER FUNCTION curr_bal (num IN INTEGER) RETURN REAL );

At run time, when the data structure is filled with values, you have created an instance of an abstract bank account. You can create as many instances (called objects) as you need. Each object has the number, balance, and status of an actual bank account.

Support for Object-Oriented ProgrammingObject types are an ideal object-oriented modeling tool, which you can use to reducethe cost and time required to build complex applications. Besides allowing you to create software components that are modular, maintainable, and reusable, object

Page 101

Page 102: Oracle Questions

Oracle_Questionstypes allow different teams of programmers to develop software components concurrently. By encapsulating operations with data, object types let you move data-maintenance code out of SQL scripts and PL/SQL blocks into methods. Also, object types hide implementation details, so that you can change the details without affecting clientprograms.

In addition, object types allow for realistic data modeling. Complex real-world entities and relationships map directly into object types. That helps your programs better reflect the world they are trying to simulate.

What Is an Object Type?An object type is a user-defined composite datatype that encapsulates a data structure along with the functions and procedures needed to manipulate the data. Thevariables that form the data structure are called attributes. The functions and procedures that characterize the behavior of the object type are called methods. We usually think of an object (such as a person, car, or bank account) as having attributes and behaviors. For example, a baby has the attributes gender, age, and weight, and the behaviors eat, drink, and sleep. Object types let you maintain thisperspective when you sit down to write an application.

When you define an object type using the CREATE TYPE statement, you create an abstract template for some real-world object. The template specifies only those attributes and behaviors the object will need in the application environment. For example, an employee has many attributes, but usually only a few are needed to fill the requirements of an application Suppose you must write a program to allocate employee bonuses. Not all employee attributes are needed to solve this problem. So, you design an abstract employee who has the following problem-specific attributes: name, id_number, department, job title, salary, and rank. Then, you identify the operations needed to handle an abstract employee. For example, you need an operationthat lets Management change the rank of an employee. Next, you define a set of variables (attributes) to represent the data, and a set ofsubprograms (methods) to perform the operations. Finally, you encapsulate the attributes and methods in an object type. The data structure formed by the set of attributes is public (visible to client programs). However, well-behaved programs donot manipulate it directly. Instead, they use the set of methods provided. That way,the employee data is kept in a proper state.(Future releases of Oracle will let you define private data structures, which can bemanipulated only by the methods you provide.) At run time, when the data structure is filled with values, you have created an instance of an abstract employee. You cancreate as many instances (usually called objects) as you need. Each object has the name, number, job title, and so on of an actual employee (see Figure 9-2). This datais accessed or changed only by the methods associated with it. Thus, object types let you create objects with well-defined attributes and behavior. Figure 9-2: Object Type and Objects (Instances) of That Type

Future releases of PL/SQL will support inheritance, a mechanism that lets you definespecialized object types, which automatically derive the attributes and methods of amore general object type. Why Use Object Types?Object types reduce complexity by breaking down a large system into logical entities. This allows you to create software components that are modular, maintainable, and reusable. It also allows different teams of programmers to developsoftwarecomponents concurrently. By encapsulating operations with data, object types let you move data-maintenance code out of SQL scripts and PL/SQL blocks into methods. Object types minimize side effects by allowing access to data only through approved operations. Also, object types hide implementation details, so that you can change the details without affecting client programs. Object types allow for realistic data modeling. Complex real-world entities and

Page 102

Page 103: Oracle Questions

Oracle_Questionsrelationships map directly into object types.Moreover, object types map directly into classes defined in object-oriented languages such as C++. Now your programs canbetter reflect the world they are trying to simulate. Structure of an Object TypeLike a package, an object type has two parts: a specification and a body (refer to Figure 9-3). The specification is the interface to your applications; it declares a data structure (set of attributes) along with the operations (methods) needed to manipulate the data. The body fully defines the methods, and so implements the specification.

*****This is general topic on Oracle 8(sql)SQL PLUS ENHANCEMENTS IN ORACLE8.0

SQL*Plus Release 8.0 Enhancements

SQL*Plus Release 8.0 is a superset of SQL*Plus Release 3.3.

To fully exploit SQL*Plus Release 8.0, you need Oracle8. SQL*Plus Release 8.0 gives you the following capabilities:

There is a new command named ATTRIBUTE. The ATTRIBUTE command displays attributes for a given column, and functions similar to the COLUMN command. There is a new command named PASSWORD. The PASSWORD command allows passwords tobe changed without echoing the password to an input device. The CONNECT command will now prompt a user to change their password if it has expired. The EXIT command now has a :BindVariable clause. The :BindVariable clause represents a variable created in SQL*Plus with the VARIABLE command, and then referenced in PL/SQL or other subprograms. :BindVariable exits the subprogram and returns you to SQL*Plus. The LONG and LONGCHUNKSIZE datatypes determine the limits for the CLOB and NCLOB datatypes. The SET command now has a LOBOFFSET clause. The LOBOFFSET clause sets the starting position from which CLOB and NCLOB data is retrieved. The SET NEWPAGE command now has a NONE clause. A value of NONE, prints no blanklines and no formfeed between report pages. The SET command now has a SHIFTINOUT clause. The SHIFTINOUT clause allows correct alignment for terminals that display shift characters. This command can only be used with shift sensitive character sets. The SHOW ERRORS command now includes the TYPE and TYPE BODY clauses. The VARIABLE command now includes the clauses NCHAR, NVARCHAR2 (NCHAR VARYING),CLOB and NCLOB.The maximum length of CHAR and NCHAR bind variables have been increased to 2000. The maximum length of VARCHAR2 and NVARCHAR2 have been increased to 4000.NCHAR datatype A standard Oracle datatype. The NCHAR datatype specifies a fixed-width nationalcharacter set character string, and can have a maximum column size up to 2000 bytes.

NVARCHAR2 datatype A standard Oracle datatype. The NVARCHAR2 datatype specifies a variable-length NCHAR string. NVARCHAR2 width specifications refer to the number of characters if the national character set is fixed-width, and to the number of bytes if the national character set is varying-width. The maximum column size allowed is 4000 bytes. CLOB datatype A standard Oracle datatype. The CLOB datatype is used to store single-byte character large object data, and can store up to 4 gigabytes of character data.

Datatype Description Column Length and Default CHAR (size) Fixed-length character data of length size bytes. Fixed for every row in the table (with trailing blanks);

Page 103

Page 104: Oracle Questions

Oracle_Questions maximum size is 2000 bytes per row, default size is 1 byte per row. Consider the character set (one-byte or multibyte) before setting size. VARCHAR2 (size) Variable-length character data. Variable for each row, up to 4000 bytes per row. Consider the character set (one-byte or multibyte) before setting size. A maximum size must be specified. NCHAR(size) Fixed-length character data of length size characters or bytes, depending on the national character set. fixed for every row in the table (with trailing blanks). Column size is the number of characters for a fixed-width national character set orthe number of bytes for a varying-width national character set. Maximum size is determined by the number of bytesrequired to store one character, with an upper limit of2000 bytes per row. Default is 1 character or 1 byte,depending on the character set. NVARCHAR2 (size) Variable-length character data of length size characters or bytes, depending on national character set. A maximum size must be specified. Variable for each row. Column size is the number of characters for a fixed-width national character set or the number of bytes for a varying-width national characterset. Maximum size is determined by the number of bytes required to store one character, with an upper limit of 4000 bytes per row. Default is 1 character or 1 byte, depending on the character set. CLOB Single-byte character data. Up to 2^32 - 1 bytes, or 4 gigabytes. NCLOB Single-byte or fixed-length multibyte national character set (NCHAR) data. Up to 2^32 - 1 bytes, or 4 gigabytes. LONG Variable-length character data. Variable for each row in the table, up to 2^31 - 1 bytes, or 2 gigabytes, per row. Provided for backward compatibility. NUMBER (p, s) Variable-length numeric data. Maximum precision p and/or scale s is 38.Variable for each row. The maximum space required for a given column is 21 bytes per row. DATE Fixed-length date and time data, ranging from Jan. 1, 4712 B.C.E. to Dec. 31, 4712 C.E. Fixed at 7 bytes for each row in the table. Defaultformat is a string (such as DD-MON-YY) specified by NLS_DATE_FORMAT parameter. BLOB Unstructured binary data. Up to 2^32 - 1 bytes, or 4 gigabytes. BFILE Binary data stored in an external file. Up to 2^32 - 1 bytes, or 4 gigabytes. RAW (size) Variable-length raw binary data. variable for each row in the table, up to 2000 bytes per row. A maximum size must be specified. Provided for backward compatibility. LONG RAW Variable-length raw binary data.Variable for each row in the table, up to 2^31 - 1 bytes, or 2 gigabytes, per row. Provided for backward compatibility. ROWID Binary data representing row addresses.

Page 104

Page 105: Oracle Questions

Oracle_Questions Fixed at 10 bytes (extended ROWID) or 6 bytes (restricted ROWID) for each row in the table. MLSLABEL Trusted Oracle datatype. See the Trusted Oracle Server Administrator's Guide.

FREQUENTLY ASKED QUESTIONS IN ORACLE(SQL) ----------------------------------------- AND TIPS FOR DBA,GENERAL ------------------------

1. Query to Display Duplicate Rows ------------------------------- Select * From Dept X Where Rowid Not In (Select Min(Rowid) From Dept Where Deptno=X.Deptno)

2. Query to Display Alternate Rows ------------------------------- Select Empno,Ename From Emp Where (Empno,Rownum) In (Select Empno,Mod(Rownum,2) From Emp)

3. Query to Display Other Alternate Rows ------------------------------------- Select * From Emp Where Rowid Not In (Select Rowid From Emp Where (Empno,Rownum) In (Select Empno,Mod(Rownum,2) From Emp))

4. Query to Delete Alternate Rows ------------------------------ Delete From Emp Where (Empno,Rownum) In (Select Empno,Mod(Rownum,2) From Emp);

5. Query to Print Some Text ------------------------ Select Empno,Deptno,Decode(Mod(Rownum,5),0,'*****') Print From Emp;

6. Query to Get Column Without Specifying The Column Name ------------------------------------------------------ Select &N,&Q From Emp Where Deptno=10;

7. To Delete Dup Rows But Leaving One Row Undeleted On Specific Cond ----------------------------------------------------------------- Delete From Emp Where Deptno=10 And Rowid Not In(Select Min(Rowid) From Emp Where Deptno=10)

8. To Delete Dup Rows But Leaving One Row Undeleted ------------------------------------------------ Delete From EMP X Where Rowid Not In(Select Min(Rowid) From EMP Where Deptno= X.Deptno)

9. To Select All Columns,Rowid Without Specifying The Column Name -------------------------------------------------------------- Select Rowid,Emp.* From Emp

10.To Select Requested Columns,Rowid Without Specifying The Column NamePage 105

Page 106: Oracle Questions

Oracle_Questions --------------------------------------------------------------------- Select Rowid,&N From Emp

11.To Print Static Text --------------------- Select Empno,Sal,'Maximum' From Emp Where Sal=(Select Max(Sal) From Emp) Union Select Empno,Sal,' ' From Emp Where Sal!=(Select Max(Sal) From Emp)

12.To Select The output With Sp.Character -------------------------------------- Select * From XX Where XX Like '\_' Escape '\' Select * From Emp Where Ename Like '%\_%' Escape '\';

13.To Select Deleted Record After Commit ------------------------------------- Select XX From Test1 Union Select XX+1 From Test1 Minus (Select XX From Test1 )

14.To Print Min & Max ------------------ Select Empno,Sal,'Maximum' From Emp Where Sal = (Select Max(Sal) From Emp) Union Select Empno,Sal,' ' From Emp Where Sal != (Select Max(Sal) From Emp) And Sal != (Select Min(Sal) From Emp) Union Select Empno,Sal,'Minimum' From Emp Where Sal = (Select Min(Sal) From Emp) 15.To Find The Maximum Sal as per Request -------------------------------------- Select Distinct Sal From Scott.Emp A Where &N=(Select Count(Distinct(Sal)) From Emp B Where A.Sal <=B.Sal)

16.Sql Execution Path ------------------ USER REQUEST TO SERVER LISTENER TAKES REQUEST DATA DICTIONARY CHECKS FOR VALID USER PARSE TREE BREAKS UP THE STATEMENT INTO COMPONENTS DATA DICTIONARY CHECKS FOR ACCESS AND MANY EXECUTION PLAN CREATE PLAN FOR EXECUTION OF STATEMENT IN THE BEST POSSIBLE WAY DATA IS GIVEN BACK TO USER

15.Print the following data in the given Output format --------------------------------------------------- SFLG AMT ---- ---- DB 10 CR 20

OUTPUT ------ DB CR AMT --- -- ---- 10 0 10 0 20 20

Select Decode(CRDR,'CR',To_Char(Amount),'DR',0) "CR",Page 106

Page 107: Oracle Questions

Oracle_Questions Decode(CRDR,'DR',To_Char(Amount),'CR',0) "DR" ,Amount From Cre

17.How to Drop More Than One Table By Single Drop Statement -------------------------------------------------------- IF It Is Clustered Then It Is Possible Drop Cluster Clustername Including Table.

18.Can Sequence Be Rolled Back --------------------------- NO It cannot be rolled back.

19.Can Sequence Be Altered. ------------------------ Except Startwith Others can be altered

20.Frame a query which displays rows between nth to mth row -------------------------------------------------------- Select * From Emp Where Rownum < &a Minus Select * From Emp Where Rownum < &b;

21.Frame a query which displays the particular row ----------------------------------------------- Select * From Emp Where Rownum < &&a Minus Select * From Emp Where Rownum < &&a-1

22.Query to print the Cumulative sum of salary ------------------------------------------- Select Sum(a.sal) From Scott.Emp A ,Scott.Emp B Where A.Empno <= B.Empno Group By B.Empno

23.Query to list the Plan table in Tree structured form ---------------------------------------------------- Select Lpad(' ', 2 * ( Level -1 )) ||Operation||'--'||Options||'-'|| Object_Name ||'-'|| Decode(id,0,'Cost = '||Position) "Query Plan" From Plan_Table Start With id = 0 and Statement_id = '&stid' Connect By Prior id = Parent_id and Statement_id = '&stid' 24.To Rename A Column For A Table ------------------------------ Update Col$ Set Name = '&NEWNAME' Where Name = '&COLUMNNAME' And Obj# = (Select Obj# From Obj$ Where Name='&TABLENAME' And Owner# =(Select User# From User$ Where Name='&USERNAME')) Hint : Use it from SYS

25.To Find The Up Time Of The Database ----------------------------------- 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(Mod(Sec.Value,60),'09'),2,2) Started From V$Instance JUL, V$Instance SEC, V$Thread C Where JUL.Key Like '%JULIAN%' AND SEC.Key Like '%SECOND%'

26.To List the Employees data in Tree Structured Form -------------------------------------------------- Select Substr(Lpad(' ',2*(Level-1))||Job,1,20) JOB,Mgr,Empno

Page 107

Page 108: Oracle Questions

Oracle_Questions From Emp Connect By Prior Empno=Mgr Start With Mgr Is Null

27.To List the missing Numbers in the following table -------------------------------------------------- Table Name: - T1 ---------------- Column name - C1: ---------------- Data - 1 4 7 8 9 10 ---- Answer : -------- select '1' from dual union select '2' from dual union select '3' from dual union select '4' from dual union select '5' from dual union select '6' from dual union select '7' from dual union select '8' from dual union select '9' from dual union select '10' from dual minus select * from t1

28.How can we calculate the total number of rows in oracle database and in this way get size of database? ----------------------------------------------------- There are three ways used to find the number of rows in the database:

1) Use the ANALYZE built-in package to estimate or compute statistics for all users, then issue

SELECT SUM(NUM_ROWS) FROM ALL_TABLES;

2) Export the database with FULL=Y. The output of the export will display the number of records for each table. You will manually add the numbers.

3) SELECT COUNT(*) from all tables. Since there could be a large number of tables, you can write a script to dynamically create another script:

set header off set feedback off spool count_it.sql SELECT 'SELECT COUNT(*) FROM '||owner||'.'||table_name||';' FROM ALL_TABLES; spool off

Now, you have a script, "count_it.sql" that contains multiple SELECT COUNT(*) statements. Run count_it.sql and add up the totals.

The above three methods are good to find the number of records. Since there is overhead, such as free space within a block, and since each table has differing data and column types, the number of records does not always give an indication of the size of the data. To do this, type:

SELECT COUNT(distinct substr(rowid,1,8)) FROM table_name;

This will give the number of physical database blocks that the table data occupies. Usually a database block is 2k, 4k or 8k. You should be able to get the block size by looking at your initSID.ora file or configSID.ora file. Do the above script for all tables.

Page 108

Page 109: Oracle Questions

Oracle_Questions

29. Find out the DB Efficiency. --------------------------- select round((1-(pr.value/(bg.value+cg.value)))*100,2) from v$sysstat pr, v$sysstat bg, v$sysstat cg where pr.name = 'physical reads' and bg.name = 'db block gets' and cg.name = 'consistent gets'

The init.ora parameter: DB_BLOCK_BUFFERS controls the amount of memory allocated for the data cache. When an application requests data, Oracle first attempts to find it in the data cache. The more often Oracle finds requested data in memory a physical IO is avoided, and thus overall performance is better. Under normal circumstances this ratio should be greater than or equal to 95%. Initially set the DB_BLOCK_BUFFERS size to be 20 - 50% the size of the SGA.

30. a) After an index has been created on a table, how can one check whether it is a B-tree index or a bitmap index? Is there any data dictionary view where I can see that info? b) Given that indexes are expensive to update, which would be more expensive for update - a B-tree index or a bitmap index? ------------------------------------------------------------------------ a) DBA_/ALL_/USER_INDEXES.UNIQUENESS column will contain keyword BITMAP. b) Bitmap will generally be more expensive due to the need to uncompress then recompress the bitmap.

31. How does the optimiser decide to do a full table scan or indexed scan of a table? (based on Analyse table and other parameters) ------------------------------------------------------------------------ Optimizer first compares the potential IO and then the CPU overhead. IO overhead depends on number of reads to complete a full table scan, obtaining DB_FILE_MULTIBLOCK_READ_COUNT at a time from disk versus the number of different blocks that would be read from the table to meet the expected rows found via the index. Issues include whether or not the WHERE clause includes actual values or bind variables, how many columns in the WHERE clause participate in available indexes, whether or not the table has been analyzed, etc.

32. What is the maximum number of concurrent transactions each rollback segment can support? -------------------------------------------------------------------- There is no parameter that controls the number of transactions that a rollback segment can handle, it is function of DB_BLOCK_SIZE. The parameter TRANSACTIONS_PER_ROLLBACK_SEGMENT does not control the number of txns a rollback segment can handle, instead is used to compute the number of public rollback segments that need to be brought online, after x number of private rollback segments have been brought online, subject to the ratio of TRANSACTIONS/TRANSACTIONS_PER_ROLLBACK_SEGMENT.

33. Which processes have what priorities in Oracle? Does the LGWR process has the highest priority, but what of the rest? -------------------------------------------------------------------- All processes in Oracle need to run at the same priority. They get there work done on time either by *waking up* each or through the use of timers. If they were to work at different priorities, some operating systems can get them to a point where one process gets more resources than it can use in a single time-slice and the other processes don't get sufficient time to re-acquire the resources they need. A long time ago I was able to demonstrate this on a VAX/VMS system by setting wildly different values to the various background and server processes -- running a simulated load of 200 users, I was able to *freeze* the database in less than 30 minutes.

Page 109

Page 110: Oracle Questions

Oracle_Questions

34. Which V$ table or other view will show us the database is in RESTRICTED SESSION? ---------------------------------------------------------------------- v$instance, in 7.3.2 it shows RESTRICTED MODE with a value of 4096 for restricted and a value of 0 for unrestricted mode.

Tips for Efficient SQL ---------------------- * do not perform calculations on an indexed column, it negates the index * use UNION instead of OR * use NOT EXISTS instead of NOT IN or HAVING * avoid using LIKE, it will negate indexes and cause a full table scan * do not mix datatypes, use numbers to numeric datatypes and same for alphanumeric datatypes * driving table is last table in FROM clause (Rule-based optimizer) * avoid subqueries, use a JOIN * use DECODE to reduce the number of table accesses * disable an index by concatenating a null or 0 to the column name (name||'' orsalary+0) * use a full table scan is returning more that 20% of the rows in the table * use table aliases with column names

35. Finding the nth largest value (for example, the fifth largest salary) in a table can be done in many ways, but the code in this example makes it possible to do it in a single query by passing the nth value as a parameter to the query. Example table - empdetails Empno number Empname varchar Salary number

SELECT MAX(salary) FROM empdetails WHERE LEVEL = &1 CONNECT BY PRIOR salary > salary START WITH salary = (SELECT MAX(salary) FROM empdetails)

36. Query to find the number of Blocks used by the data in a table : ---------------------------------------------------------------- select COUNT(DISTINCT(SUBSTR(ROWID,1,8)||SUBSTR(ROWID,15,4))) Blocks_Used from table_name; When you replace "table_name" with the name of a table in your database, the query below will return the number of blocks used by the data in that table. The query examines the Block_ID (columns 1-8) and the File_ID (columns 15-18) of the ROWID. The query then returns the number of distinct blocks used by the records within the table. The ANALYZE command can also provide this information, but this query is faster.

37. A Generic Script for Creating Indexes ------------------------------------- This script generates another script that will include create index statements for all the indexes in your database. REM REM SCRIPT FOR CREATING INDEXES REM REM This script must be run by a user with the DBA role. REM REM Running this script will in turn create a script to build all the REM indexes in the database. This created script, create_index.sql, REM can be run by any user with the DBA role or with the 'CREATE ANY INDEX' REM system privilege.

Page 110

Page 111: Oracle Questions

Oracle_Questions REM REM The script will NOT capture the indexes created by the user 'SYS'. REM REM set verify off; set termout off; set feedback off; set echo off; set pagesize 0; set termout on select 'Creating index build script...' from dual; set termout off; create table i_temp (lineno NUMBER, id_owner VARCHAR2(30), id_name VARCHAR2(30), text VARCHAR2(800)) / DECLARE CURSOR ind_cursor IS select owner, index_name, table_owner, table_name, uniqueness, tablespace_name, ini_trans, max_trans, initial_extent, next_extent, min_extents, max_extents, pct_increase, pct_free from dba_indexes where owner != 'SYS' order by index_name; CURSOR col_cursor (i_own VARCHAR2, c_ind VARCHAR2, c_tab VARCHAR2) IS select column_name from dba_ind_columns where index_owner = i_own and index_name = c_ind and table_name = c_tab order by column_position;

v_index_owner dba_indexes.owner%TYPE; v_index_name dba_indexes.index_name%TYPE; v_table_owner dba_indexes.table_owner%TYPE; v_table_name dba_indexes.table_name%TYPE; v_uniqueness dba_indexes.uniqueness%TYPE; v_tablespace_name dba_indexes.tablespace_name%TYPE; v_ini_trans dba_indexes.ini_trans%TYPE; v_max_trans dba_indexes.max_trans%TYPE; v_initial_extent dba_indexes.initial_extent%TYPE; v_next_extent dba_indexes.next_extent%TYPE; v_min_extents dba_indexes.min_extents%TYPE; v_max_extents dba_indexes.max_extents%TYPE; v_pct_increase dba_indexes.pct_increase%TYPE; v_pct_free dba_indexes.pct_free%TYPE; v_column_name dba_ind_columns.column_name%TYPE; v_first_rec BOOLEAN; v_string VARCHAR2(800); v_lineno number := 0;

procedure write_out(p_line INTEGER, p_owner varchar2, p_name VARCHAR2, Page 111

Page 112: Oracle Questions

Oracle_Questions p_string VARCHAR2) is begin insert into i_temp (lineno,id_owner, id_name,text) values (p_line,p_owner,p_name,p_string); end;

BEGIN OPEN ind_cursor; LOOP FETCH ind_cursor INTO v_index_owner, v_index_name, v_table_owner, v_table_name, v_uniqueness, v_tablespace_name, v_ini_trans, v_max_trans, v_initial_extent, v_next_extent, v_min_extents, v_max_extents, v_pct_increase, v_pct_free; EXIT WHEN ind_cursor%NOTFOUND; v_lineno := 1; v_first_rec := TRUE; if (v_uniqueness = 'UNIQUE') then v_string:= 'CREATE UNIQUE INDEX ' || lower(v_index_owner) || '.' || lower(v_index_name); write_out(v_lineno, v_index_owner, v_index_name, v_string); v_lineno := v_lineno + 1; else v_string:= 'CREATE INDEX ' || lower(v_index_owner) || '.' || lower(v_index_name); write_out(v_lineno, v_index_owner, v_index_name, v_string); v_lineno := v_lineno + 1; end if;

OPEN col_cursor(v_index_owner,v_index_name,v_table_name); LOOP FETCH col_cursor INTO v_column_name; EXIT WHEN col_cursor%NOTFOUND; if (v_first_rec) then v_string := ' ON '|| lower(v_table_owner) || '.' || lower(v_table_name)||' ('; v_first_rec := FALSE; else v_string := v_string || ','; end if; v_string := v_string || lower(v_column_name); END LOOP; CLOSE col_cursor; v_string := v_string || ')'; write_out(v_lineno, v_index_owner, v_index_name, v_string); v_lineno := v_lineno + 1; v_string := null; v_string := 'PCTFREE ' || to_char(v_pct_free); write_out(v_lineno, v_index_owner, v_index_name, v_string); v_lineno := v_lineno + 1; v_string := 'INITRANS ' || to_char(v_ini_trans) || ' MAXTRANS ' || to_char(v_max_trans); write_out(v_lineno, v_index_owner, v_index_name, v_string); v_lineno := v_lineno + 1;

Page 112

Page 113: Oracle Questions

Oracle_Questions v_string := 'TABLESPACE ' || v_tablespace_name || ' STORAGE ('; write_out(v_lineno, v_index_owner, v_index_name, v_string); v_lineno := v_lineno + 1; v_string := 'INITIAL ' || to_char(v_initial_extent) || ' NEXT ' || to_char(v_next_extent); write_out(v_lineno, v_index_owner, v_index_name, v_string); v_lineno := v_lineno + 1; v_string := 'MINEXTENTS ' || to_char(v_min_extents) || ' MAXEXTENTS ' || to_char(v_max_extents) || ' PCTINCREASE ' || to_char(v_pct_increase) || ')'; write_out(v_lineno, v_index_owner, v_index_name, v_string); v_lineno := v_lineno + 1; v_string := '/'; write_out(v_lineno, v_index_owner, v_index_name, v_string); v_lineno := v_lineno + 1; v_lineno := v_lineno + 1; v_string:=' '; write_out(v_lineno, v_index_owner, v_index_name, v_string); END LOOP; CLOSE ind_cursor; END;

spool create_indexes.sql set heading off set pagesize 5000

col text format a80 word_wrap select text from I_temp order by id_owner, id_name, lineno; spool off drop table i_temp; exit

38.Finding the Nth Largest Value, Part II -------------------------------------- The use of the index and the hint make this one of the fastest solutions of its kind. Also, the solution is flexible enough to accept the value as a parameter (&n) and to allow you to choose any or all column(s) of the row. This query also returns all rows standing at the Nth largest position, which can be filtered out using a group function, to display only one row. (e.g. avg()/max()/min()) However, you must use Oracle 7.3 or higher, you must use hint 'index_desc', and an index must exist on the desired column. /* Original EMP table */ create table emp (empno number, salary number ) /

/* Index to be used with the hint */ create index emp_sal on emp (salary) /

/* The solution */

/* Here we have a dummy where the clause which helps choose the index and the use of the hint ensures that only the emp_sal index is used. */

Page 113

Page 114: Oracle Questions

Oracle_Questions

select * from emp where salary = (select /*+ index_desc(emp_sal) */ min(salary) from emp where salary > 0 and rownum

39. Generalised Function to Convert Numbers to Words ------------------------------------------------ Create function amount_spFormula(amount in number) return Char is temp_amount varchar2(60); Begin If instr(to_char(amount),'.') = 0 then temp_amount := to_char( to_date( substr( to_char(amount), 1),'j'),'Jsp') ; Elsif instr(to_char(amount),'.') >= 1 then temp_amount := to_char( to_date( substr( to_char(amount), 1 ,instr(to_char(amount),'.')-1), 'j'),'Jsp') ; End if; return temp_amount; End;

40. Query to Display Line Numbers with a gap of Five(Any Number) ------------------------------------------------------------ select empno,ename,decode(mod(rownum,5),0,rownum,null) Line from emp;

Page 114