FOREIGN KEY constraint A constraint that establishes a parent child relationship between two tables via one or more

common columns. The foreign key in the child table refers to a primary or unique key in the parent table. Transaction A logical unit of work consisting of one or more SQL statements that must all succeed or all fails to keep the database in a logically consistent state. A transfer of funds from one bank account is a logical Transaction, in that both the withdrawal from one account and the deposit to another account must succeed for the transaction to succeed. Schema A named group of objects associated with a particular user account, such as tables, indexes, functions, and so forth. Relational table The most common form of a table in the Oracle database; the default type created with the CREATE TABLE statement. A relational table is permanent and can be partitioned. External table A table whose definition is stored in the database but whose data is stored externally to the database. Index A database object designed to reduce the amount of time it takes to retrieve rows from a table. An index is created based on one or more columns in the table. Composite index If an index that is created on two or more columns in a table. This is called as Composite index. Sequence

It is a database structure that automatically generates a series of numbers typically used to assign primary key values to database tables. Synonyms A synonym is an alias for another database object, such as a table, sequence, or view. Synonyms provide easier access to database objects outside the user’s schema. There are two kinds of synonyms: public and private. Public synonyms are Available to all database users. A private synonym is available only in the session of the schema owner who created it. Username An Oracle database account identifier that, along with a password, allows a user to connect to the database. Privileges The right to perform a specific action in the database granted by the DBA or other database users. System privileges Privileges that allow users to perform a specific action on one or more database objects or users in the database. Object privileges Privileges that allow users to manipulate the contents of database objects in other schemas. ROWID A unique identifier for a row in a table, maintained automatically in the table by the Oracle server. ROWIDs are unique throughout the database. Unique Index In a Unique index, there are no duplicate values. An error is returned if you try to insert two rows into a table with the same index column values. By default, an index is nonunique. Bitmap index

An index that maintains a binary string of ones and zeros for each distinct value of a column within the index. Materialized View A materialized view can help speed queries by storing data in a previously joined or summarized format. Unlike a traditional view, this stores only the query and runs that query every time the view is accessed; a materialized view stores the results of the query in addition to the SQL statements of the view itself. Because the materialized view already contains the results of the view’s underlying query, Using a materialized view can be as fast as accessing a single table. OR What is materialized view? A materialized view is a database object that contains the results of a query. They are local copies of data located remotely, or are used to create summary tables based on aggregations of a table's data. Materialized views, which store data based on remote tables are also, know as snapshots.A materialized view can query tables, views, and other materialized views. Collectively these are called master tables (a replication term) or detail tables (a data warehouse term) Alias An alternate name for a column, specified right after the column name in a SELECT statement, seen in the results Of the query.

DML (Data Manipulation Language) Includes INSERT, UPDATE, DELETE, and MERGE statements that operate specifically on database tables. Occasionally, SELECT statements are included in the SQL DML category. DUAL A special table, owned by the Oracle SYS user, that has one row and one column. It is useful for ad hoc queries that don’t require rows from a specific table.

NULL A NULL is usually used to represent a value that is unknown, not applicable, or not available. Why order by clause maintains column number values instead of column names? Every Column have unique number in the table, when we write ORDER BY Clause with number then it refers to that unique number and display the result. You can see the column Id as per below query SELECT COLUMN_NAME, COLUMN_ID FROM USER_TAB_COLUMNS WHERE TABLE_NAME = 'EMP' What is difference between SQL and SQL*PLUS? SQL*PLUS is a command line tool where as SQL and PL/SQL language interface and reporting tool. Its a command line tool that allows user to type SQL commands to be executed directly against an Oracle database. SQL is a language used to query the relational database(DML,DCL,DDL). SQL*PLUS commands are used to format query result, Set options, Edit SQL commands and PL/SQL. There are 10 rows in Table A and 0 Rows in table B. Select * from A,B How many rows will be retrieved. Ans : it will not select any row.coz according to this query it has to give cartesian product.that means it will select m into n rowsso 10*0=0 No Rows Selected. What is the difference between Rename and Alias? Rename is a permanent name given to a Table or Column Whereas Alias is a temporary name given to a table or a column, which do not exist once the SQL statement is executed. What is the Difference between stored procedures a... An external procedure, also sometimes referred to as an external routine, is a procedure stored in a dynamic link library (DLL), or libunit in the case of a Java class method. You register the procedure with the base language, and then call it to perform special-purpose

deptno. What is Complex View?Where we can use? Views containing any group functions or joining tables are known as complex views. A stored procedure is a group of SQL statements that form a logical unit and perform a particular task.0) from dual. In which case we are using case and in which case we are using decode? With an example? ecode is a function where case is expression . This will be stored in oracle database.ename.2) from emp) select * from emp where (rowid.null. Write query for the following questions select * from emp where (rowid. decode gives result different when using null see below SQL> select decode( null. select * from emp where rowid in ( select rowid from emp where rownum <=&upto minus select rowid from emp where rownum <&startfrom) Difference between decode and case. dept d where (+)e.how do you get the entire department and corresponding employee details and the department which are not allotted it? We use joins to get details from both the tables that’s kind of joins r called outer joins to get the missed statements.1.eno.mod(rownum.0) . select e.0) not in (select rowid.mod(rownum. e.0) in (select rowid.1.2) from emp) How to retrieving the data from 11th column to n th column in a table.NULL.deptno from emp e. e. We have EMP and dept table .processing.deptno=d. DECODE(NULL.

disadvantages 1. security will be there. you can use two tables data in view.. 2. 3. A 'Mutating table’ is a table which is being updated by Insert. 2. What are the advantages and disadvantages of View?. update or delete triggers. Explain what is mutation and what is mutating table and how this mutation problem is solved in a table? Mutation happens in case of triggers.when table is not there view will not work. It can also be a table which is being updated when delete cascade is run.--------------------1 1* select case null when null then 1 else 0 end from dual SQL> / CASENULLWHENNULLTHEN1ELSE0END ----------------------------0 but see here SQL> select case when null is null then 1 else 0 end from dual. advantages 1. dml is not possible if that is more than one table. 3. hiding the data. 2) In Decode Else can be specifed in the statement it self but in Case a seperate statement has to be written. it is also database object so it will occupy the space. CASEWHENNULLISNULLTHEN1ELSE0END ------------------------------1 The Main Difference is that 1) Decode cannot be used in Where clause but Case can. ..

but. current date ----------------24-mar-06. for eg:select sysdate "current date" from dual. Find the two minimum salaries among table Ans: select sal from (select * from <table_name> order by sal asc) where rownum < 3 how to get the prime number rows from table ie like1. What is the difference between single quote (') and double quote(") in relates to using in SQL. U may create a function like this . To solve this either we have to use intermediate table or a view so that it can choose from one while updating the other.5.double quotes are used to print the name in sql screen.3.Mutation occurs when a trigger is trying to update a row which it is using currently. How to get first 5 Records then next 5 records till end of row count in SQL – Oracle ? elect * from emp where rownum<6 Then we can get the next 5 records by the following sql: select * from emp where rownum<6 MINUS select * from emp where rownum<11 and so on. When do you use 'xxx' and "xxx"? what is the difference both of them? ingle quote is used to write a character string or character in sql query.11 Ans : I tried in sql but sql is not sufficient.7..

end if. RN COL1 C ---------.a. Assumuming the table as follows SQL> select * from dummyag.col1. if v_flag=1 then return 0.create or replace function fn_chk_pm(v_num in number) return number is v_flag number:=0.v_cnt)=0 then v_flag:=1.rn.- .rn!=1 With the result. if v_flag=0 then return 1.rn)=1 3* and a.v_j loop if mod(v_num. end if.col1. exit when v_flag=1.---------. v_j number:=round(v_num/2).col2 from dummyag) a 2 where fn_chk_pm(a. begin for v_cnt in 2.. COL1 COL2 ---------. end if. end.col2 from (select rownum rn.2b 3c 4d 1a I can call it from sql statement as follows: SQL> 1 select a.a. end loop.

'j').2 3 3c 4d Ans 2 : ((select * from emp where (rowid. the output like.mod(rownum. (to_char(to_date(sal.')) "Sal in Words" from emp / Salary Sal in Words .1) in (select rowid. 'jsp')) from emp.'J'). (' Rs.mod(rownum. SAL (TO_CHAR(TO_DATE(SAL.----------------------------------------------------800 eight hundred 1600 one thousand six hundred 1250 one thousand two hundred fifty If you want to add some text like. Three Thousand only. 'Jsp'))|| ' only.'j').3) from emp))) union (select * from emp where (rowid. Display the number value in Words? DELETE It is a DML statement We can Rollback Has Does Does not require SQL> select sal. Differentiate between TRUNCATE and DELETE TRUNCATE It is a DDL statement It is a one way trip.'JSP')) --------.3) in (select rowid. '|| (to_char(to_date(sal. cannot ROLLBACK Doesn't have selective features (where clause) Doesn't fire database triggers It requires disabling of referential constraints. SQL> select sal "Salary ". Rs.0) in (select rowid.rownum from emp)).2) from emp)) Minus (select * from emp where (rowid.

. a. One Thousand Two Hundred Fifty only. 1250 Rs. One Thousand Six Hundred only.------. the record discarded it fetches 2nd record makes it rownum 1 again that is why rownum=x does'nt work How do we display the column values of a table? DECLARE CURSOR cr_data IS SELECT ROWID.* FROM fnd_user a where rownum < 10. How to get the 25th row of a table select * from emp where rowid=(select max(rowid) from emp where rownum<26) OR elect * from Emp where rownum < 26 minus select * from Emp where rownum<25 Why equality condition does'nt work with rownum. it fetches first record makes it rownum 1 as it does'nt match the where criteria. i'm giving my explanation here? the query select * from emp where rownum=25.IMP--This table name should be same as your from table in the above cursor l_value VARCHAR2 (2000). 1600 Rs. l_table_name VARCHAR2(2000) := 'FND_USER'. Eight Hundred only. -.-----------------------------------------------------800 Rs.

column_name || ' from '||l_table_name||' where rowid = '||chr(39) || cr_rec.column_name .ROWID||chr(39). CURSOR column_names (p_table_name VARCHAR2) IS SELECT * FROM all_tab_columns WHERE table_name = p_table_name. -. EXECUTE IMMEDIATE l_str INTO l_value. DBMS_OUTPUT.We should pass the same Table Name FOR cr_columc_rec IN column_names (l_table_name) LOOP l_str := 'Select ' || cr_columc_rec. DBMS_OUTPUT. BEGIN FOR cr_rec IN cr_data LOOP -.put_line ('Query is ' || l_str).You can use order by clause here if you want.l_str VARCHAR2 (2000).put_line ( 'Column is ' || cr_columc_rec.

. What is the diff between %Rowtype and %type? %Rowtype means associating a single variable to a entire row. drop. from which the view was created. and schema trigger? Instead of trigger : A view cannot be updated . logon / logoff of the user.. where we can write the code so that the data will be updated in the table. like alter. Database trigger : this trigger will be fired when a database event ( dml operation ) occurs in the database table. then this trigger can be used .|| ' and Value is ' || l_value ). Tell me the difference between instead of trigger. begin . database trigger. update or delete.(It is one way of Declaring a composite plsql datatype "RECORD") %type means associating a single variable to a particular column in table. END. both %Rowtype and %type declarations are known as Anchored Declarations in plsql . truncate etc. System triggers : this trigger will fire for database events like dtartup / shutdown of the server. and server errors . like insert . so if the user tries to update a view. END LOOP. Wat is difference between Cursor and Ref Cursor ? • Cursor is static one and ref cursor is dynamic with return type Example for cursor: declare cursor c1 is select * from emp. END LOOP. and also for the ddl events.

Public function and procedure declarations procedure tabledata(tname in varchar2.Author : RPSINGH -. .v_cur out my_cur) is begin OPEN V_CUR FOR 'SELECT * FROM '||TNAME.put_line(r1. end emp_data. v_cur out my_cur). end.ename). -. / Example for ref cursor CREATE OR REPLACE package emp_data is -.Purpose : displaying the data from different tables -.Public constant declarations -. / CREATE OR REPLACE PACKAGE BODY EMP_DATA IS procedure tabledata(tname in varchar2.for r1 in c1 loop dbms_output.Created : 8/17/2006 12:54:03 AM -. end loop.Public type declarations type my_cur is ref cursor.empno||' '||r1.Public variable declarations -.

end tabledata. END LOOP.FIRST_NAME||' '||V_CUR. C_CUR). LOOP FETCH C_CUR INTO V_CUR. / Now to use this code: declare v_cur employees%rowtype. / Cursor is a structure which points to a memory locations While Ref-cursor is a data structure which point to a object which intern points to Memory locations. begin emp_data.MY_CUR. EXIT WHEN C_CUR%NOTFOUND. DBMS_OUTPUT. end emp_data. Advantage of having Ref-cursor is that we can pass dynamically the Ref-cursor as a parameter to a procedure. END.PUT_LINE(V_CUR. Can we create a table using with Procedure or Function? DECLARE BEGIN .tabledata('EMPLOYEES'.LAST_NAME). C_CUR EMP_DATA.

refer above example sal_rec table will hold data only till programme is reaching to end. 2. v_sal sal_rec.count loop dbms_output. end loop.EXECUTE IMMEDIATE 'create table employee(empno number(3).occurs when row level trigger accesses same table on which it is based while executing or the table currently being modified by the DML statements. What is the Mutating trigger error? Mutating error:. end. v_sal. example: declare type sal_rec is table of number.. for r in 1. END. What is the difference between Oracle table & PL/SQL table? Table is logical entity which holds the data in dat file permanently. begin select sal bulk collect into v_sal from emp. where as scope of plsql table is limited to the particular block / procedure . What is instead trigger 3.ename varchar2(10))'. 1.What is bulk collect? Bulk collect is part of PLSQL collection where data is stored/ poped up into a variable. How to find the nth hightest record holder from a table .put_line(v_sal(r)).

just scroll the mouse and u can see the last column . or INSERTS statement. the effects of the trigger body and triggering statement are rolled back. Â Desc table name. a PL/SQL table. If you need to update a mutating table. This Mutating Trigger restriction applies only to the for each row triggers. For example.sal).sal)) from t1 b where a. a runtime error occurs. DELETE. and control is returned to the user or application. and an AFTER statement trigger that updates the original table with the values from the temporary table.suppose i have table called T1 with 2 columns say ID. you could bypass these restrictions by using a temporary table. or a package variable.sal from t1 a where 3 =(select count(distinct(b. When a trigger encounters a mutating table.sal <= b.SAL then i want to find out 3rd highest salary select a. resulting in a mutating table error. how can i get set identity for last coloumn of the table SELECT * FROM USER_TAB_COLUMNS WHERE TABLE_NAME=V_TABLE_NAME AND ROWNUM=1 ORDER BY COLUMN_ID DESC OR Easy Way: just describe the table name. you might use two triggers--an AFTER row trigger that updates a temporary table. in place of a single AFTER row trigger that updates the original table. OR select * from emp where rownum <=9 minus select * from emp where rownum <9 Mutating Table: A mutating table is a table that is currently being modified by an UPDATE.

You cannot pass cursor variables to a procedure that is called through a database link. SQL> conn maria/maria. -. nested table. the following declaration is not allowed:CREATE PACKAGE emp_stuff AS TYPE EmpCurTyp IS REF CURSOR RETURN emp%ROWTYPE. There is no equivalent type to use in a CREATE TABLE statement. or nullity.What are the Restrictions on Cursor Variables? cursor variables are subject to the following restrictions:You cannot declare cursor variables in a package spec.Database columns cannot store the values of cursor variables.You cannot use comparison operators to test cursor variables for equality. SQL> CREATE OR REPLACE PROCEDURE ddl_create_proc (p_table_name IN VARCHAR2) 2 3 AS 4 5 l_stmt VARCHAR2(200). For example.. How we can create a table in PL/SQL block.You cannot assign nulls to a cursor variable. If you need to perform manipulations from the output of the select statement which results multiple rows. you can avoid using cursor: for instance: select fname into v_fname from emp where empno = 10. Connected. . emp_cv EmpCurTyp. SQL> set serverout on.You cannot store cursor variables in an associative array. insert records into it??? is it possible by some procedure or function?? please give example. For example. you cannot use one where the other is expected. you cannot reference a cursor variable in a cursor FOR loop.. inequality. you cannot fetch from it on the server side unless you also open it there on the same server call.Cursors and cursor variables are not interoperable. the cursor need to be used. If you pass a host cursor variable to PL/SQL. or varray.not allowedEND emp_stuff. How to avoid using cursors? What to use instead of cursor and in what cases to do so? If your select statement retruns only one value. that is.

6 7 BEGIN 8 9 DBMS_OUTPUT. Connected.------. SQL> set serverout on SQL> exec ddl_create_proc('tony_emp'). STARTING exception ORA-01031: insufficient privilegesmessage-1031 PL/SQL procedure successfully completed. SQL> conn maria/maria.put_line('STARTING ').put_line('exception '||SQLERRM || 'message'||sqlcode). SQL> grant create table to maria identified by maria. Connected. SQL> set server output on SQL> exec ddl_create_proc('tony_emp'). 16 17 EXCEPTION 18 19 WHEN OTHERS THEN 20 21 DBMS_OUTPUT. 12 13 execute IMMEDIATE l_stmt. 14 15 DBMS_OUTPUT.---------EMP TABLE TONY_1 TABLE TONY_4 TABLE TONY_EMP TABLE SQL> select * from emp where rownum < 3. STARTING end PL/SQL procedure successfully completed.put_line('end '). SQL> conn system/manager. 22 23 END. Grant succeeded. SQL> select * from tab. TNAME TABTYPE CLUSTERID -----------------------------. 10 11 l_stmt := 'create table '|| p_table_name || ' as (select * from emp )'. ID ---------- . 24 / Procedure created.

if you grant permission to others.rownum?what are the psoducolumns we have? ROWID .. they will also be able to access that procedure or function) in the database.. Explain rowid.. you define once.. In Oracle terms. ID ---------1 2 SQL> spool off Forward Declaration in Packages and Functions from PLSQL Forward Declaration means. and you can call that procedure or function from other part of application.1 2 SQL> select * from tony_emp where rownum < 3.It is a integer number also unique for sorting Normally TOP N Analysis. stored function and application function. to affect with the commit or rollback of the Surrounding transactions.. Used in searching ROWNUM . If u want to use second procedure in the definition of first procedure. a PL/SQL block which is stored (meaning. Here you can ask the question "What are the other types of procedure or functions available in Oracle?". Other Pseudo Column are NEXTVAL. Here is the simple example to understand this:- . you can have a procedure or function defined within a pl/sfql block. Moreover. This enables you to call that pro/function from that pl/sql block only.. CURRVAL Of sequence are some examples What is difference b/w stored procedures and application procedures.. It’s labeled as forward declaration. If you are defining a package body having two procedures . You have to declare the second package with its arguments (if have) before using in the definition of first procedure. The answer is.Hexa decimal number each and every row having unique. you can define pro/function in packages as well. What is autonomous Transaction? Where are they use Autonomous Transaction is a feature of oracle 8i which maintains the state of Its transactions and save it .

X ---------1 . 10 InsertInTest_Table_B. 7 END . 8 BEGIN 9 INSERT INTO Test_Table_A(x) values (123). Ora816 SamSQL :> Select * from Test_Table_A. 13 / PL/SQL procedure successfully completed.Ora816 SamSQL :> declare 2 Procedure InsertInTest_Table_B 3 is 4 BEGIN 5 INSERT into Test_Table_B(x) values (1). X ---------123 ora816 SamSQL :> Select * from Test_Table_B. 12 END. 6 Commit. 11 Rollback.

PRAGMA AUTONOMOUS_TRANSACTION overrides this behavior. commits the transaction at Line-no 5 and line-no 9. 9 BEGIN 10 INSERT INTO Test_Table_A(x) values (123). 11 InsertInTest_Table_B. 14 / PL/SQL procedure successfully completed. . ora816 SamSQL :> Select * from Test_Table_A. 5 BEGIN 6 INSERT into Test_Table_B(x) values (1). Ora816 SamSQL :> declare 2 Procedure InsertInTest_Table_B 3 is 4 PRAGMA AUTONOMOUS_TRANSACTION. 8 END.Notice in above pl/sql COMMIT at line no 6 . 7 Commit. The Rollback at line-no 11 actually did nothing. Let us the see the following example with PRAGMA AUTONOMOUS_TRANSACTION. 12 Rollback. 13 END. Commit/ROLLBACK at nested transactions will commit/rollback all other DML transaction before that.

no rows selected ora816 SamSQL :> Select * from Test_Table_B. the transaction state maintained independently . It is advisable to increase the value of TRANSACTIONS parameter in the INIT parameter file to allow for the extra concurrent transaction . or initialized variable . Out. What is the difference between In. X ---------1 With PRAGMA AUTONOMOUS_TRANSACTION . constant. InOut Parameters. expression. Commit/Rollback of nested transaction will no effect the other transaction. Ans: In 1 Default mode 2 Value is passed into subprogram 3 Formal parameter acts as a constant 4 Actual parameter can be a literal. Can we pass value or reference or both to the In Out Parameter.

returned to calling environment 3 Initialized variable 4 Must be a variable 5 Cannot be assigned a default value .5 Can be assigned a default value OUT 1 Must be specified 2 Returned to calling environment 3 Uninitialized variable 4 Must be a variable 5 Cannot be assigned a default value INOUT 1 Must be specified 2 Passed into subprogram.

D := A + B + C. Here is the example for using out parameter in functions CREATE OR REPLACE FUNCTION TEST_FUNC(A IN NUMBER. BEGIN B := B + A. By default a function would return only one value.Can we pass value or reference or both to the In Out Parameter.C OUT NUMBER) RETURN NUMBER IS D NUMBER(3). Yes. Declare multiple variables as out parameters in the function/procedure being used . C1 NUMBER (3):= 30. END. 3. 2. . For returning multiple values declare a ref cursor in package spec and use the same in the function/procedure in the package body. B IN OUT NUMBER. This will also return multple values. RETURN D. we can by using NOCOPY keyword How to return more than one value from a function? 1. C := B. DECLARE A1 NUMBER (3):= 10. B1 NUMBER (3):= 20.

but the changes made by the previous DML statements in the transaction are not discarded. With Oracle 9. it s effect is undone by a statement-level rollback. for security and hiding the table column infor. we used normally view. of triggers that can be created on a table? With Oracle 10g: any number of trigger can be written on a table. Is there any limitation on no. Materalized view is used for remote data access and suitable for transaction related data storage in distributed environment.PUT_LINE (A1 || ' ' || B1 || ' ' || C1 || ' ' || D1). B1. BEGIN D1:= TEST_FUNC (A1.D1 NUMBER (3):= 40. . END. What happens when DML Statement fails? A.Statement Level Rollback C. AND C1). we uses for Report & MIS purposes for showing the data from more than two table. They can be committed or rolled back explicitly by the user.0 or below�: �� max 12 Based on what conditions can we decide whether to use a table or a view or a materialized view ? Tables we used for entity information physically in our DB.User level rollback B. DBMS_OUTPUT. and forcefully/manually. View is a virtual representation of table data.Sustem Level Rollback Ans: If a single DML statement fails during execution of a transaction. It stores the data phyisically comparision to normal view. It can refreshes the remote data auto.

Can e truncate some of the rows from the table instead of truncating the full table. if you have two databases and you want a view in both databases . sales NUMBER(10. for view . You can truncate few rows from a table if the table is partitioned.OR Table is the basic entity in any RDBMS .this view ia mainly used in datawarehousing .if you have complex query from which you want to extract data again and again . keep view as read only (FOR SHOWING REPORTS) for materialized view . moreover it is a standard data which is required by many other user also for REPORTS generation then create view . main advatages of materialized view over simple view are [1] it save data in database whether simple view's definition is saved in database [2] can create parition or index on materialize view to enhance the performance of view . Avoid to insert / update / delete through view unless it is essential. Here is the example: CREATE TABLE parttab ( state VARCHAR2(2).2)) PARTITION BY LIST (state) ( . but cannot on simple view. so for storing data you need table . when to create materialized view[1] if data is in bulk and you need same data in more than one database then create summary table at one database and replica in other databases [2] if you have summary columns in projection list of query. You can truncate a single partition and keep remaining. What are ref cursors ? They are similar to a normal cursor but they can have different select statements at run time. So create a summary table in a database and make the replica(materialized view) in other database. remember in datawarehousing we deal in GB or TB datasize .

'CA') TABLESPACE uwdata). 400000). • Functions called from SQL statements cannot . you can write the PL/SQL code in exception part. • Functions called from UPDATE/DELETE statements On a table T cannot contain DML on the same table T. SELECT * FROM parttab. ALTER TABLE parttab TRUNCATE PARTITION southwest. 100000). 300000). Suppose you want to insert the exception detail into your error log table. PARTITION southwest VALUES ('AZ'. INSERT INTO INSERT INTO INSERT INTO INSERT INTO COMMIT. ('CA'. 200000). To handle the exception which may be raised in your exception part. SELECT * FROM parttab. • Functions called from an UPDATE or a DELETE Statement on a table T cannot query the same table. What are the restrictions on Functions? Restrictions on Calling Functions from SQL Expressions: • Functions called from SQL expressions cannot Contain DML statements.PARTITION northwest VALUES ('OR'. ('WA'. that time you can write insert into statement in exception part. 'WA') TABLESPACE uwdata. ('AZ'. can i write plsql block inside expection Yes you can write PL/SQL block inside exception section. parttab parttab parttab parttab VALUES VALUES VALUES VALUES ('OR'.

What type of binding is PL/SQL? The assigning of values to PL/SQL variables in SQL statements is called binding. increases efficiency because the definitions of database objects are looked up then. Variables in the package specification are called global variables . If the collection has 20 elements. This technique improves performance by minimizing the number of context switches between the PL/SQL and SQL engines. UPDATE. or DELETE statements using a single operation. On the other hand. called dynamic or late binding.Contain statements that end the transactions. increases flexibility because the definitions of database objects can remain unknown until then. INSERT. • Calls to subprograms that break the previous Restrictions are not allowed in the function. binding at run time. entire collections. Functions must return a single value. PL/SQL binding operations fall into three categories: • • • in-bind out-bind define A DML statement can transfer all the elements of a collection in a single operation. With bulk binds. bulk binding lets you perform the equivalent of 20 SELECT. How a database language implements binding affects runtime efficiency and flexibility. Binding at compile time. are passed back and forth. No. Why Functions are used in oracle ? Can Functions Return more than 1 values? Why Procedures are used in oracle ? What are the Disadvantages of packages? What are the Global Variables in Packages? Ans: functions are return a value. not just individual elements. a process known as bulk binding. not at run time. called static or early binding. Procedure is used to perform an action.

BEGIN …….. How do you find which procedure produced the error? How do you find which section of the code produced the error and look at? Ans: There are a number of ways to understand the exact line which has the error. Thus. code_desc) VALUES(‘1403’. EXCEPTION WHEN NO_DATA_FOUND THEN INSERT INTO err_log( err_code. Can we use commit or rollback command in the exception part of PL/SQL block? Yes we can use commit/rollback in exception part.OR A function can return more than one value.. It can be done by using out parameters with the variables. which returns the error number. 1) Using the SQL+ . and calling them in the return clause. 2) Programmatically.it will return on base of select statement. You have compiled some PL/SQL packages in your schema. along with the exception handling section The second method usually brings more good as it is experienced that at time the line number mentioned by oracle isn’t the real trouble maker. use a variable to store a prominate place holder at the major junctions of the code and publish the same by catching the error in the exception handling section. ‘No data found’) .. datatype and size. OR Function can able to return more than one value using ref cursor. type in show err command. Example: DECALRE …. and found some errors in one procedure. This method proves to be specially useful when the code is rather bulky.

when others then . Commit. end. END OR try this code create table test1(x varchar2(20)) declare x number.empno%type. exception when others then dbms_output. begin select empno into v_empno from emp where empno = 10. begin select sal into x from emp where ename like 'TTT%'. What is the output of the following pl/sql block? declare v_empno emp. / Select * from test1.put_line ( 'no data found').put_line ( 'ther is no data found '). exception when no_data_found then Insert into test1 values ('no data'). end.COMMIT. when no_data_found then dbms_output. RAISE.

Plsql Procedure successfully completed. update.empno%type. Where as a procedure may or may not return a value or may return more than one value using the OUT parameter. A PROCEDURE may return one or more values through parameters or may not return at all. What is difference between a PROCEDURE & FUNCTION? A FUNCTION is always returns a value using the return statement. OR 1. Functions are normally used for computations where as procedures are normally used for executing business logic. 4.put_line ( 'no data found').* ERROR at line 6: ORA-06550: line 6. exception when no_data_found then dbms_output. you cannot call such a function in a SQL query. begin select empno into v_empno from emp where empno = 10. column 2: PLS-00370: OTHERS handler must be last among the exception handlers of a block ORA-06550: line 0. Procedure can return multiple values (max 1024). Function is mainly used in the case where it must return a value. . Function returns 1 value only.put_line ( 'ther is no data found '). 5.  2. column 0: PL/SQL: Compilation unit analysis terminated Ans : declare v_empno emp. delete) statements in a function. end. Function can be called from SQL statements where as procedure can not be called from the sql statements 3. But. You can have DML (insert. when others then dbms_output.

2.Since packages has specification and body separate so. varying number of parameters is called overloading of procedures. 3. 7. Â 9.A procedure may modify an object where a function can only return a value The RETURN statement immediately completes the execution of a subprogram and returns control to the caller. Where as function return type could be scalar or table or table values 8. Stored procedure is precompiled execution plan where as functions are not. only body gets invalidated and not the spec. You can declare a trigger as Autonomous by providing PRAGMA AUTONOMOUS_TRANSACTION in the beginning of the trigger. At a same time you have to end your trigger with commit/rollback. Stored Procedure: supports deferred name resolution.but actually not exists in database is allowed only in during creation but runtime throws error Function wont support deferred name resolution. So any other proc/func dependent on package does not gets invalidated. Generally In triggers you can't use TCL commands. whole package is loaded into memory and hence all objects of pack is available in memory which means faster execution if any is called. whenever any ddl is run and if any proc/func(inside pack) is dependent on that.Stored procedure returns always integer value by default zero. You can use these types of triggers to maintain log details of a table. It possible to use Transaction control Statements such a ROLLBACK or COMMIT in Database Trigger?. And since we put all related proc/func in one package this feature is useful as we may need to run most of the objects. But you can use TCL commands in Autonomous Triggers.Whenever any func/proc from package is called.6. The main advantages of packages are 1..we can declare global variables in the package What are the components of a PL/SQL BLOCK? PL/SQL Block contains: .. What is Overloading of procedures? The Same procedure name is repeated with parameters of different data types and parameters in different positions. Example while writing a stored procedure that uses table named tabl1 and tabl2 etc.

. Exception: Optional Any errors to be trapped End: Mandatory So only begin and end keywords are required. Following are the data type supported in oracle PLSQL Scalar Types BINARY_INTEGER DEC DECIMAL DOUBLE PRECISION FLOAT INT INTEGER NATURAL NATURALN NUMBER NUMERIC PLS_INTEGER POSITIVE POSITIVEN REAL SIGNTYPE SMALLINT CHAR CHARACTER LONG LONG RAW NCHAR NVARCHAR2 RAW ..Declare: optional Variable declaration Begin: Mandatory Procedural statements. as needed. What are the data types a available in P. to process a pl/sql block.

g. . e_rec c1 %ROWTYPE.deptno from emp. e_rec emp% ROWTYPE cursor c1 is select empno. TYPE rec RECORD is to be used whenever query returns columns of different table or views and variables.ename emp ename %type ). E. TYPE r_emp is RECORD (eno emp.empno% type.ROWID STRING UROWID VARCHAR VARCHAR2 DATE INTERVAL DAY TO SECOND INTERVAL YEAR TO MONTH TIMESTAMP TIMESTAMP WITH LOCAL TIME ZONE TIMESTAMP WITH TIME ZONE BOOLEAN Composite Types RECORD TABLE VARRAY LOB Types BFILE BLOB CLOB NCLOB Reference Types REF CURSOR REF object_type What is difference between % ROWTYPE and TYPE RECORD ? % ROWTYPE is to be used whenever query returns a entire row of a table or view.

UPDATEs. Instead you can use PL/SQL loops to move through the contents of a PL/SQL table. begin for v_emp in c_example loop statements . This is a programmatic construct in a programmatic language. this type stores data in a record fashion with 2 columns. You cannot issue DML statements (INSERTs.3 does offer a DELETE operator). You cannot SELECT from PL/SQL tables. end. There is no way to perform set-at-atime processing to retrieve data from a PL/SQL table... You cannot commit information to a PL/SQL table or roll back changes from the table.. tables with data structure format etc. What is a cursor ? Why Cursor is required ? . b varchar2(10)). one row at a time.. and DELETEs) against PL/SQL tables (though PL/SQL Release 2. the type record is a object oriented concept related to pl/sql tables. declare cursor c_example is select * from emp.OR basically the %rowtype is used in case of fetching the values of the cursor irrespective of how many columns in it and also the data types associated with the tables column.for eg.. create type ty_name is record ( a number. What is PL/SQL table ? Keep the following restrictions in mind when you work with PL/SQL tables: • • • There is no concept of transaction integrity with PL/SQL tables. v_emp emp%rowtype. end loop.

Cursor is a named private SQL area from where information can be accessed. (2) Never user CURSOR keyword explicitly (3) Memory allocation and program controls will done automatically (4) Returns or updates or deletes only one record. cursor retrive data from a table.Whenever we execute sql statements oracle server assigns a work . Cursors are required to process rows individually for queries returning multiple rows. Reference Cursor IMPLICIT. SQL%NOTFOUND EXPLICIT ----------(1) called as cursors (2) Uses CURSOR keyword explicitly (3) Memory allocation and program control thru the cursor written. %ISOPEN. (5) Attributes : SQL%FOUND. (4) Returns or updates or deletes A multiple records. Dynamic Cursor 3. Implicit Cursors: . SQL%NOTFOUND. (5) Attributes : SQL%FOUND. OR Cursors are of two types 1. %ROWCOUNT Use of Cursor: Cursors are required to process rows individually for queries returning multiple rows. it can be done in two level 1 %type it retrive data from a particular row 2 %rowtype it retrive data from a full table there are three types of cursors 1. Static Cursor * Implicit Cursor * Explicit Cursor 2. EXPLICIT IMPLICIT ----------(1) Called as SQL.

use the WHERE CURRENT OF clause. Old values are NULL for insert statement.. 2. Declaring a cursor :. The most recently used work are can be accessed using SQL%.In explicit cursor you can explicitly assign a name to process information stored in private sql areas. fetch. Open the cursor :.Releases the cursor Explain the usage of WHERE CURRENT OF clause in cursors? When referencing the current row from an explicit cursor. III. This allows you to apply updates and deletes to the row currently being addressed. II. UPDATE statement has access to both old and new values. INSERT statement has access only to new values. Enforce complex business rules Derive column values automatically. In implicit cursors open.the procedure should be declared as an AUTONOMOUS TRANSACTION. What happens if a procedure that updates a column of table X is called in a database trigger of the same table ? To avoid the mutation table error . What are two virtual tables available during database trigger execution? OLD and NEW are two virtual tables available during database trigger execution. New values are NULL for delete statement. Maintain replicate tables. OR What is a database trigger? Name some usages of database trigger? Database trigger is stored PL/SQL program unit associated with a specific database table. This process involves four steps I. Implement complex security authorizations.Involves assign a name to cursor and associating a query with it. Usages are Audit data modifications. Log events transparently. Fetch the cursor :. Close the cursor :.area called private sql area to store processed information.Explicit cursors:.Executes the query and identify the result set. close operations are automatically performed by the server implicitly. You must include the FOR UPDATE clause in the cursor query to lock the rows first.gets the result set and Loops through to process them IV. . DELETE statement has access only to old values. without the need to explicitly reference the ROWID.

What is an Exception ? What are types of Exception ? Exception is the error handling part of PL/SQL block. • . IF confidition the RAISE EXCEPTION or RAISE_APPLICATION_ERROR What is Pragma EXECPTION_INIT ? Explain the usage ? The PRAGMA EXECPTION_INIT tells the complier to associate an exception with an oracle error. EXCEPTIONS • Predefined Do not declare and allow the Oracle server to rise implicitly NO_DATA_FOUND TOO_MANY_ROWS INVALID_CURSOR ZERO_DIVIDE INVALID_CURSOR WHEN EXCEPTION THEN … Non predefined Declare within the declarative section and allow allow Oracle server to raise implicitly o SQLCODE – Returns the numeric value for the seeor code o SQLERRM – Returns the message associated with error number DECLARE -.By this the procedure will be treated as an separate identity. To get an error message of a specific oracle error.PRAGMA EXCEPTION_INIT (exception. error_number) RAISE – WHEN EXCEPTION_NAME THEN … • User defined Declare within the declarative section and raise explicitly.

e.g. Pragma exception_init(FOUND_NOTHING . dbms_output. What is Raise_application_error ? Raise_application_error is a procedure of package DBMS_STANDARD which is used to create your own error messages which can be more descriptive than named exceptions. oracle error number) example declare salary number.error_messages). FOUND_NOTHING exception. .100). Syntax is:Raise_application_error (error_number. error_number).Syntax PRAGMA EXCEPTION_INIT(exception. PRAGMA EXCEPTION_INIT (exception name. begin select sal in to salaryfrom emp where ename ='ANURAG'.put_line(salary). exception WHEN FOUND_NOTHING THEN dbms_output. where error_number is between -20000 to -20999.put_line(SQLERRM). end.

What are the modes of parameters that can be passed to a procedure? . What is a stored procedure? A stored procedure is a subprogram that is stored in the database as a PCODE (Pre Compiled Code) and thus called as a standalone schema object.What are the return values of functions SQLCODE and SQLERRM ? Pl / Sql Provides Error Information via two Built-in functions. c) It can be nested d) is created by using the syntax CREATE OR REPLACE e) this stored procedure can be seen as an object in the User_Objects and is different from the procedures that are created in packages. SQLCODE & SQLERRM. SQLERRM Returns the Current Error Message Text. It may or may not return a value. Reusability. Modularity. Returns “User Defined Exception " Where the Pre_defined_exceptions are stored ? PL/SQL declares predefined exceptions in the STANDARD package. f) Procedures promote reusability and maintainability What are advantages fo Stored Procedures / Extensibility. This attribute differentiates it from another subprogram type called FUNCTION. Returns 1. b) It is similar to any subprogram that accepts parameters and performs an action. or other subprograms. SQLCODE Returns the Current Error Code. a) It can be invoked directly from any calling environments. Maintainability and one time compilation.

What are two parts of package ? The two parts of package are PACKAGE SPECIFICATION & PACKAGE BODY. end function_name. Package Specification contains declarations that are global to the packages and local to the schema. Both Package Spec and Package Body are stored separately in the Data base Package specifications act as an interface for the Package What is difference between a Cursor declared in a procedure and Cursor declared in a package specification ? . Package Body contains actual procedures and local declaration of the procedures and cursor declarations. return value.IN (default): Passes a constant value from the calling environment into the procedure OUT :Passes a value from the procedure to the calling environment IN OUT :Passes a value from the calling environment into the procedure and a possibly different value from the procedure back to the calling environment using the same parameter Give the structure of the function? create or replace function function_name(formal parameters list with only IN mode) return datatype is local variable declarations begin executable statments.

col3 number) alter table tab1 add(col2 char). Name the tables where characteristics of Package. procedure and functions are stored ? User_objects.col3 from tab1. ALL_SOURCE. ALL_ERRORS. User_Source and User_error.A cursor declared in a package specification is global and can be accessed by other procedures or procedures in a package.but however if u want u can do so like ----> you can use dbms_redefination package . A cursor declared in a procedure is local to the procedure that can not be accessed by other procedures. DBA_ERRORS Inserting column in existing table As all the two moderators said it's not important to do so. ALL_OBJECTS.it matters only with view. But you should have these previleges --> # execute access on the dbms_redefinition package # create any table # alter any table # drop any table # lock any table # select any table create table tab1(col1 char.col2. DBA_SOURCE c) USER_DEPENCENCIES d) USER_ERRORS.'tab1'). create table tab2 as select col1.can_redef_table('schema_name'. OR The Data dictionary tables/ Views where the characteristics of subprograms and Packages are stored are mentioned below a) USER_OBJECTS. DBA_OBJECTS b) USER_SOURCE. begin . exec dbms_redefinition.

You can copy both the data and the structure but not the constraints.'tab1'. O/P: HiAll For e. SELECT TRANSLATE('Hi All'.'') FROM DUAL.'H') FROM DUAL.e.e.'col1. select *from tab1.start_redef_table('schema_name'.col2. O/P: No o/p Again if i try the following query i. When a query is executed and the indexed column is used system retrieves the records very fast by using the address of data stored in indexes.'@'. SELECT REPLACE('Hi All'. O/P: HiAll But if i try the same query with translate function i am getting no o/p i. Difference in translate and replace If i try the following query it works fine in replacing the spaces between two words i. 'tab1'.col3').' '.'A') .'tab2'. You need to do so manually.dbms_redefinition. How do indexes function? Indexes store the address of data not the data itself. SELECT TRANSLATE('Hi All'.e. Create the table manually by running the same script as of the existing table and run another query to copy the data. col1 col2 col3 --------------Copy Constraints How to create a table from another table with constraints it is not possible to create a table from another table with constraints. 'tab2' ).'') FROM DUAL. dbms_redefinition. end.'H '.finish_redef_table( 'schema_name'.g. SELECT TRANSLATE('@sia'.' '.

Ex: OrderID Line_no Part_no Order1 1 abc Order1 2 abc Order1 3 Order1 4 Order1 5 abc Order1 6 abc I need to eliminate lines 3 and 4 (null Part_no).' '. and recreate the table as: OrderID Line_no New_Line_no Part_no Order1 1 1 abc . --------------------------------------------------------------------Need Query I have a table Orders (order_id.FROM DUAL. if I've the data as follows: Name Value ==== ==== Name1 V11 Name1 V12 Name1 V13 Name2 V21 Name2 V22 I want the OUTPUT to be as follows: Name1 V11 V12 V13 Name2 V21 V22 Apperciate if anyone can help me out in this. line_no.'') FROM DUAL. part_no). O/P: Asia (WORKS FINE) But SELECT TRANSLATE(' Asia'. O/P: No o/p (FAILS) How do I transpose Rows into Columns? How do I transpose Rows into Columns? For example.

ROWNUM new_line_no. part_no FROM orders WHERE part_no IS NOT NULL . line_no.Order1 Order1 Order1 2 5 6 2 3 4 abc abc abc How do I write a query to do this? Ans: SELECT orderid.

Sign up to vote on this title
UsefulNot useful