Collection of SQL queries with answers

Share Embed Donate


Short Description

Collection of SQL Queries with answers... interview questions.....

Description

SQL

Disadvantages of trigger in oracle? Triggers can execute every time some field in database is updated. If a field is likely to be updated often, it is a system overhead. Viewing a trigger is difficult compared to tables, views stored procedures. It is not possible to track or debug triggers. ------------------------------------------------------------------------------------------------------------------------------------Create a query that will display the total no.of employees and, of that total, t he no.of employees hired in 1995,1996,1997, and 1998. create appropriate column headings. SELECT to_char(hiredate,yyyy),count(*) FROM emp GROUP BY to_char(hiredate,yyyy) HAVING to_char(hiredate,yyyy) IN (1995,1996,1997,1998); select Count(*) as NumberOfEmployees, EmployeesHiredIn1995_1996_1997_1998 = (select count(*) from employees where hiredate like '%1995%' or hiredate like '%1996%' or hiredate like '%1997%' or hiredate like '%1998%') from employees select count(*) from employees where hiredate in(1995,1996,1997,1998); select count(*) Count, to_char(hiredate, 'YYYY') YEAR from emp group by rollup( to_char(hiredate, 'YYYY')) Select count(emp_code), count(case when TO_NUMBER(to_CHAR(hire_date,'YYYY'))=1995 then (emp_code) s hire_1995 count(case when TO_NUMBER(to_CHAR(hire_date,'YYYY'))=1996 then (emp_code) s hire_1996 from employees --similary the query will continue. remember that the fields are from one and you are not doing any dimension querying. only the fact info is being d

select count(decode(to_char(hiredate, count(decode(to_char(hiredate, count(decode(to_char(hiredate, count(decode(to_char(hiredate, count(*) total_emp from emp;

'yyyy') 'yyyy') 'yyyy') 'yyyy')

, , , ,

'1995', '1996', '1997', '1998',

hiredate, hiredate, hiredate, hiredate,

select to_char(PADATEOFJOININGD,'YYYY'), count(*)

null)) null)) null)) null))

end) a end) a table querie

hired_in_1995, hired_in_1996, hired_in_1997, hired_in_1998,

from PAEMPLOYEE_M group by (to_char(PADATEOFJOININGD,'YYYY')) union select 'total emplyee', count(*) from PAEMPLOYEE_M SELECT COUNT(*) TOTAL_EMP, SUM(CASE WHEN INSTR(HIREDATE,'81') SUM(CASE WHEN INSTR(HIREDATE,'80') SUM(CASE WHEN INSTR(HIREDATE,'87') SUM(CASE WHEN INSTR(HIREDATE,'82') FROM EMP

> > > >

0 0 0 0

THEN THEN THEN THEN

1 1 1 1

ELSE ELSE ELSE ELSE

0 0 0 0

END)HIRED_81, END)HIRED_80, END)HIRED_87, END)HIRED_82

select count(*) Count, to_char(hiredate, 'YYYY') YEAR from emp group by to_char( hiredate, 'YYYY') having substr(to_char(hiredate,'yyyy'),-1) in(5,6,7,8)

Please check with this query... SELECT COUNT(EMPID) TOTAL_EMPS, DECODE(TO_CHAR(HIRE_DATE,YYYY)),'1995',COUNT(EMPID)) DECODE(TO_CHAR(HIRE_DATE,YYYY)),'1996',COUNT(EMPID)) DECODE(TO_CHAR(HIRE_DATE,YYYY)),'1997',COUNT(EMPID)) DECODE(TO_CHAR(HIRE_DATE,YYYY)),'1998',COUNT(EMPID)) FROM EMP

TOTAL_HIRE_1995, TOTAL_HIRE_1996, TOTAL_HIRE_1997, TOTAL_HIRE_1998

select count(*), count(decode(to_char(hiredate, 'yyyy'), 1995,1)), count(decode(to_char(hiredate, 'yyyy'), 1996,1)), count(decode(to_char(hiredate, 'yyyy'), 1997,1)), count(decode(to_char(hiredate, 'yyyy'), 1998,1)) from emp

SELECT to_char(hiredate,'YYYY'),count(*) FROM employee GROUP BY to_char(hiredate ,'YYYY'); Code SELECT hiredate,count(*) FROM ven_emp WHERE hiredate BETWEEN 01-jan-95 AND 31-dec-98 GROUP BY hiredate Code SELECT deptno,count(to_char(hiredate,yyyy),1980,empno) AS yr1980, count(to_char(hiredate,yyyy),1981,empno) AS yr1981, count(to_char(hiredate,yyyy),1982,empno) AS yr1982 FROM emp GROUP BY deptno; SELECT Hiredate,Count(*) FROM emp WHERE to_char(hiredate,yyyy) in (1995,1996,1997,1998) GROUP BY Hiredate; SELECT to_char(hiredate,YYYY),count(*) FROM employee GROUP BY to_char(hiredate,Y YYY); Code SELECT to_char(hiredate,yyyy),count(*) FROM emp GROUP BY to_char(hiredate,yyyy)

HAVING to_char(hiredate,yyyy) IN (1995,1996,1997,1998); Code SELECT COUNT(*) AS "Total" ,SUM(CASE TO_CHAR(HIRE_DATE,YYYY) WHEN 1995 THEN 1 EL SE 0 END) AS "1995", SUM(CASE TO_CHAR(HIRE_DATE,YYYY) WHEN 1996 THEN 1 ELSE 0 END) AS "1996" , SUM(CASE TO_CHAR(HIRE_DATE,YYYY) WHEN 1997 THEN 1 ELSE 0 END) AS "1997", SUM(CASE TO_CHAR(HIRE_DATE,YYYY) WHEN 1998 THEN 1 ELSE 0 END) AS "1998" FROM HR.EMPLOYEES >> > select 2 from dual; 2 ---------2 SQL> select 2,3 from dual; 2 3 ---------- ---------2 3 Was this answer useful? Reply meenatchim Nov 16th, 2008

Yes

DUAL is a table.That is owned by SYS user .It has a column name as dummy and i t containts a row having a vale "X".The dual table is useful when u want to retu n a value once only,the value that is not derived in from a table with userdata Was this answer useful? Yes Reply deepak Feb 24th, 2009

Dual is a system defined table having one rows and one column. A person who has informed that it has virtual existence is not proper. It has physical existence. Ex: SQL> select * from dual; D X Means a table having single row and columns. Regards, Deepak Mahapatra TCS Bangalore Was this answer useful? Reply samarendra161 Jul 2nd, 2010

Yes

Dual is a virtual table which contains only one row & column. Generally this tab le can be used into test predefined function functionality & also used to perfor m mathematical operation. By default dual table column datatype is varchar2. Was this answer useful? Yes Reply sk45453 Aug 23rd, 2010 Dual is a table which is created by oracle along with the data dictionary. It consists of exactly one column whose name is dummy and one record. The value of that record is X. The owner of dual is SYS but dual can be accessed by every user. As dual contains exactly one row (unless someone fiddled with it), it is guaranteed to return exactly one row in select statements. Therefore, dual is the preferred table to select a pseudo column (such as sysdate). Although it is possible to delete the one record, or insert additional records, one really should not do that! Was this answer useful? Reply Waseem Mehmood Jun 2nd, 2011

Yes

Dual is a dummy table which has one row and one column but can't make the DML op ertions. Was this answer useful? Yes Reply subrahmanyam pattapu Jul 19th, 2011 Dual is default table in oracle .it contains single row and single column.All th e Character functions and number functions and date functions execution done in this Dual table. Was this answer useful? Yes Reply shadiq Jun 25th, 2015 Insert into dual values (Y); will work i guess, only thing is you need a suffici ent privilege... Also Dual can have 1000 columns and only one row.

>> > Select Empno,Ename,Job,Sal From Emp Where SalALL:->Means More Than The Maximum Value in the List. (Q):Get The Details Of All Emps Who are Earning More than the Avg Investment of Department 10? (A): SQL>Select Empno,Ename,Job,Sal From Emp Where Sal>All(Select Avg(Sal) From Emp Where Deptno=10);

Thank you Any Mistakes please Inform to me... -Suresh

Was this answer useful? Reply saurabh Jan 30th, 2015

Yes

ANY The If any value from outcome of sub query is matched then desired output will b e retrieved. It.It checks with lowest value . ALL ALL It will check for greatest value from outcome of sub-query Was this answer useful? Yes Reply Samudrala Jan 30th, 2015 ALL The ALL comparison condition is used to compare a value to a list or subquery. I t must be preceded by =, !=, >, ALL (2000, 3000, 4000); EMPNO SAL ---------- ---------7839 5000 SQL> -- Transformed to equivalent statement without ALL.

SELECT empno, sal FROM emp WHERE sal > 2000 AND sal > 3000 AND sal > 4000; EMPNO SAL ---------- ---------7839 5000 Was this answer useful? Yes Reply Samudrala Jan 30th, 2015 ANY The ANY comparison condition is used to compare a value to a list or subquery. I t must be preceded by =, !=, >, ANY (2000, 3000, 4000); EMPNO SAL ---------- ---------7566 2975 7698 2850 7782 2450 7788 3000 7839 5000 7902 3000 SQL> -- Transformed to equivalent statement without ANY. SELECT empno, sal FROM emp WHERE sal > 2000 OR sal > 3000 OR sal > 4000; EMPNO SAL ---------- ---------7566 2975 7698 2850 7782 2450 7788 3000 7839 5000 7902 3000 >> > (select avg(salary) from dept, employee wher = employee.deptno; employee where salary>(select avg(salary) from dept, employee wher = employee.deptno;

+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_

+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_+_ +_ 1. What is PL/SQL? PL/SQL is a procedural language that has both interactive SQL and proced ural programming language constructs such as iteration, conditional branching. 2.

What is the basic structure of PL/SQL? PL/SQL uses block structure as its basic structure. Anonymous blocks or nested blocks can be used in PL/SQL. 3.

What are the components of a PL/SQL block? A set of related declarations and procedural statements is called block.

4.

What are the components of a PL/SQL Block? Declarative part, Executable part and Execption part.

5.

What are the datatypes a available in PL/SQL? Some scalar data types such as NUMBER, VARCHAR2, DATE, CHAR, LONG, BOOLEAN. Some composite data types such as RECORD & TABLE. 6. What are % TYPE and % ROWTYPE? What are the advantages of using these ov er datatypes? % TYPE provides the data type of a variable or a database column to that variable. % ROWTYPE provides the record type that represents a entire row of a table or vi ew or columns selected in the cursor. The advantages are: I. need not know about variable s data type ii. If the database definition of a column in a table changes, the data type of a variable changes accordingly. 7.

What is difference between % ROWTYPE and TYPE RECORD ? % ROWTYPE is to be used whenever query returns a entire row of a table o

r view. TYPE rec RECORD is to be used whenever query returns columns of different table or views and variables. E.g. TYPE r_emp is RECORD (eno emp.empno% type,ename emp ename %type ); e_rec emp% ROWTYPE Cursor c1 is select empno,deptno from emp; e_rec c1 %ROWTYPE. 8.

What is PL/SQL table? Objects of type TABLE are called "PL/SQL tables", which are modelled as (but not the same as) database tables, PL/SQL tables use a primary PL/SQL tables can have one column and a primary key. 9.

What is a cursor? Why Cursor is required? Cursor is a named private SQL area from where information can be accesse

d. Cursors are required to process rows individually for queries returning multiple rows. 10.

Explain the two types of Cursors? There are two types of cursors, Implict Cursor and Explicit Cursor. PL/SQL uses Implict Cursors for queries. User defined cursors are called Explicit Cursors. They can be declared and used. 11.

What are the PL/SQL Statements used in cursor processing?

DECLARE CURSOR cursor name, OPEN cursor name, FETCH cursor name INTO or Record types, CLOSE cursor name. 12.

What are the cursor attributes used in PL/SQL? %ISOPEN - to check whether cursor is open or not % ROWCOUNT - number of rows featched/updated/deleted. % FOUND - to check whether cursor has fetched any row. True if rows are featched . % NOT FOUND - to check whether cursor has featched any row. True if no rows are featched. These attributes are proceded with SQL for Implict Cursors and with Cursor name for Explict Cursors. 13.

What is a cursor for loop? Cursor for loop implicitly declares %ROWTYPE as loop index,opens a curso r, fetches rows of values from active set into fields in the record and closes w hen all the records have been processed. eg. FOR emp_rec IN C1 LOOP salary_total := salary_total +emp_rec sal; END LOOP; 14.

What will happen after commit statement ? Cursor C1 is Select empno, ename from emp; Begin open C1; loop Fetch C1 into eno.ename; Exit When C1 %notfound;----commit; end loop; end; The cursor having query as SELECT .... FOR UPDATE gets closed after COMMIT/ROLLB ACK. The cursor having query as SELECT.... does not get closed even after COMMIT/ROLL BACK. 15.

Explain the usage of WHERE CURRENT OF clause in cursors ? WHERE CURRENT OF clause in an UPDATE,DELETE statement refers to the late st row fetched from a cursor. 16.

What is a database trigger ? Name some usages of database trigger ? Database trigger is stored PL/SQL program unit associated with a specifi c database table. Usages are Audit data modificateions, Log events transparently , Enforce complex business rules Derive column values automatically, Implement c omplex security authorizations. Maintain replicate tables. 17. How many types of database triggers can be specified on a table? What ar e they? Insert Update Delete Before Row After Row

o.k. o.k.

o.k. o.k.

o.k. o.k.

Before Statement After Statement

o.k. o.k.

o.k. o.k.

o.k. o.k.

If FOR EACH ROW clause is specified, then the trigger for each Row affected by t he statement. If WHEN clause is specified, the trigger fires according to the retruned boolean value. 18. Is it possible to use Transaction control Statements such a ROLLBACK or COMMIT in Database Trigger? Why? It is not possible. As triggers are defined for each table, if you use C OMMIT of ROLLBACK in a trigger, it affects logical transaction processing. 19.

What are two virtual tables available during database trigger execution? The table columns are referred as OLD.column_name and NEW.column_name. For triggers related to INSERT only NEW.column_name values only available. For triggers related to UPDATE only OLD.column_name NEW.column_name values only available. For triggers related to DELETE only OLD.column_name values only available. 20. What happens if a procedure that updates a column of table X is called i n a database trigger of the same table? Mutation of table occurs. 21.

Write the order of precedence for validation of a column in a table ? I. done using Database triggers. ii. done using Integarity Constraints. 22.

What is an Exception? What are types of Exception? Exception is the error handling part of PL/SQL block. The types are Pred efined and user_defined. Some of Predefined execptions are. CURSOR_ALREADY_OPEN DUP_VAL_ON_INDEX NO_DATA_FOUND TOO_MANY_ROWS INVALID_CURSOR INVALID_NUMBER LOGON_DENIED NOT_LOGGED_ON PROGRAM-ERROR STORAGE_ERROR TIMEOUT_ON_RESOURCE VALUE_ERROR ZERO_DIVIDE OTHERS. 23.

What is Pragma EXECPTION_INIT? Explain the usage? The PRAGMA EXECPTION_INIT tells the complier to associate an exception w ith an oracle error. To get an error message of a specific oracle error. e.g. PRAGMA EXCEPTION_INIT (exception name, oracle error number) 24.

What is Raise_application_error? Raise_application_error is a procedure of package DBMS_STANDARD which al lows to issue an user_defined error messages from stored sub-program or database trigger.

25.

What are the return values of functions SQLCODE and SQLERRM? SQLCODE returns the latest code of the error that has occured. SQLERRM returns the relevant error message of the SQLCODE. 26.

Where the Pre_defined_exceptions are stored? In the standard package. Procedures, Functions & Packages; 27.

What is a stored procedure? A stored procedure is a sequence of statements that perform specific fun

ction. 30.

What is difference between a PROCEDURE & FUNCTION? A FUNCTION is alway returns a value using the return statement. A PROCEDURE may return one or more values through parameters or may not return a t all. 31.

What are advantages of Stored Procedures? Extensibility,Modularity, Reusability, Maintainability and one time comp ilation. 32.

What are the modes of parameters that can be passed to a procedure? IN,OUT,IN-OUT parameters.

33.

What are the two parts of a procedure? Procedure Specification and Procedure Body.

34.

Give the structure of the procedure? PROCEDURE name (parameter list.....)

is local variable declarations BEGIN Executable statements. Exception. exception handlers end; 35.

Give the structure of the function? FUNCTION name (argument list .....) Return datatype is local variable declarations Begin executable statements Exception execution handlers End;

36.

Explain how procedures and functions are called in a PL/SQL block ? Function is called as part of an expression. sal := calculate_sal ( a822 ); procedure is called as a PL/SQL statement calculate_bonus ( A822 ); 37.

What is Overloading of procedures? The Same procedure name is repeated with parameters of different datatyp es and parameters in different positions, varying number of parameters is called overloading of procedures.

e.g. DBMS_OUTPUT put_line 38.

What is a package? What are the advantages of packages? Package is a database object that groups logically related procedures. The advantages of packages are Modularity, Easier Applicaton Design, and Informa tion. Hiding,. Reusability and Better Performance. 39.

What are two parts of package? The two parts of package are PACKAGE SPECIFICATION & PACKAGE BODY. Package Specification contains declarations that are global to the packages and local to the schema. Package Body contains actual procedures and local declaration of the procedures and cursor declarations. 40. What is difference between a Cursor declared in a procedure and Cursor d eclared in a package specification? A cursor declared in a package specification is global and can be access ed by other procedures or procedures in a package. A cursor declared in a procedure is local to the procedure that can not be acces sed by other procedures. 41. How packaged procedures and functions are called from the following ? a. Stored procedure or anonymous block b. an application program such a PRC *C, PRO* COBOL c. SQL *PLUS a. PACKAGE NAME.PROCEDURE NAME (parameters); variable := PACKAGE NAME.FUNCTION NAME (arguments); EXEC SQL EXECUTE b. BEGIN PACKAGE NAME.PROCEDURE NAME (parameters) variable := PACKAGE NAME.FUNCTION NAME (arguments); END; END EXEC; c. EXECUTE PACKAGE NAME.PROCEDURE if the procedures does not have any out/in-out parameters. A function can not be called. 42. Name the tables where characteristics of Package, procedure and function s are stored? User_objects, User_Source and User_error. What are the various types of queries ? Answer: The types of queries are: Normal Queries Sub Queries Co-related queries Nested queries Compound queries ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What is a transaction ? Answer: A transaction is a set of SQL statements between any two COMMIT and ROLL BACK statements. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What is implicit cursor and how is it used by Oracle ? Answer: An implicit cursor is a cursor which is internally created by Oracle.It

is created by Oracle for each individual SQL. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Which of the following is not a schema object : Indexes, tables, public synonyms , triggers and packages ? Answer: Public synonyms ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What is PL/SQL? Answer: PL/SQL is Oracle s Procedural Language extension to SQL.The language inc ludes object oriented programming techniques such as encapsulation, function ove rloading, information hiding (all but inheritance), and so, brings state-of-theart programming to the Oracle database server and a variety of Oracle tools. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Is there a PL/SQL Engine in SQL*Plus? Answer: 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 i t much more efficient as SQL statements are not stripped off and send to the dat abase individually. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Is there a limit on the size of a PL/SQL block? Answer: Currently, the maximum parsed/compiled size of a PL/SQL block is 64K and the maximum code size is 100K.You can run the following select statement to que ry the size of an existing package or procedure. SQL> select * from dba_object_s ize where name = procedure_name ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Can one read/write files from PL/SQL? Answer: Included in Oracle 7.3 is a UTL_FILE package that can read and write fil es.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 t he 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 %sn , func1(1)); UTL_FILE.FCLOSE(fileHandler); END; ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------How can I protect my PL/SQL source code? Answer: PL/SQL V2.2, available with Oracle7.2, implements a binary wrapper for P L/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 (somewha t larger than the srcinal).This way you can distribute software without having to worry about exposing your proprietary algorithms and methods.SQL*Plus and SQL *DBA will still understand and know how to execute such scripts.Just be careful, there is no "decode" command available. The syntax is: wra p name=myscript.sql

oname=xxxx.yyy ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Can one use dynamic SQL within PL/SQL? OR Can you use a DDL in a procedure ? How ? Answer: 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; ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What are the various types of Exceptions ? Answer: User defined and Predefined Exceptions. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Can we define exceptions twice in same block ? Answer: No. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What is the difference between a procedure and a function ? Answer: Functions return a single variable by value whereas procedures do not re turn any variable by value.Rather they return multiple variables by passing vari ables by reference through their OUT parameter. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Can you have two functions with the same name in a PL/SQL block ? Answer: Yes. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Can you have two stored functions with the same name ? Answer: Yes. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Can you call a stored function in the constraint of a table ? Answer: No. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What are the various types of parameter modes in a procedure ? Answer: IN, OUT AND INOUT. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What is Over Loading and what are its restrictions ? Answer: OverLoading means an object performing different functions depending upo

n the no.of parameters or the data type of the parameters passed to it. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Can functions be overloaded ? Answer: Yes. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Can 2 functions have same name & input parameters but differ only by return data type Answer: No. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What are the constructs of a procedure, function or a package ? Answer: The constructs of a procedure, function or a package are : variables and constants cursors exceptions ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Why Create or Replace and not Drop and recreate procedures ? Answer: So that Grants are not dropped. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Can you pass parameters in packages ? How ? Answer: Yes.You can pass parameters to procedures or functions in a package. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What are the parts of a database trigger ? Answer: The parts of a trigger are: A triggering event or statement A trigger restriction A trigger action ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What are the various types of database triggers ? Answer: There are 12 types of triggers, they are combination of : Insert, Delete and Update Triggers. Before and After Triggers. Row and Statement Triggers. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What is the advantage of a stored procedure over a database trigger ? Answer: We have control over the firing of a stored procedure but we have no con trol over the firing of a trigger. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What is the maximum no.of statements that can be specified in a trigger statemen t ? Answer: One. ---------------------------------------------------------------------------------------------------------------------------------------------------------------

-------------------------------------------Can views be specified in a trigger statement ? Answer: No ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What are the values of :new and :old in Insert/Delete/Update Triggers ? Answer: INSERT : new = new value, old = NULL DELETE : new = NULL, old = old value UPDATE : new = new value, old = old value ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What are cascading triggers? What is the maximum no of cascading triggers at a t ime? Answer: When a statement in a trigger body causes another trigger to be fired, t he triggers are said to be cascading.Max = 32. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What are mutating triggers ? Answer: A trigger giving a SELECT on the table on which the trigger is written. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What are constraining triggers ? Answer: A trigger giving an Insert/Updat e on a table having referential integri ty constraint on the triggering table. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Describe Oracle database s physical and logical structure ? Answer: Physical : Data files, Redo Log files, Control file. Logical : Tables, Views, Tablespaces, etc. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Can you increase the size of a tablespace ? How ? Answer: Yes, by adding datafiles to it. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Can you increase the size of datafiles ? How ? Answer: No (for Oracle 7.0) Yes (for Oracle 7.3 by using the Resize clause ) ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What is the use of Control files ? Answer: Contains pointers to locations of various data files, redo log files, et c. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What is the use of Data Dictionary ? Answer: It Used by Oracle to store information about various physical and logica l Oracle structures e.g.Tables, Tablespaces, datafiles, etc --------------------------------------------------------------------------------

--------------------------------------------------------------------------------------------------------------------------What are the advantages of clusters ? Answer: Access time reduced for joins. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What are the disadvantages of clusters ? Answer: The time for Insert increases. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Can Long/Long RAW be clustered ? Answer: No. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Can null keys be entered in cluster index, normal index ? Answer: Yes. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Can Check constraint be used for self referential integrity ? How ? Answer: Yes.In the CHECK condition for a column of a table, we can reference som e other column of the same table and thus enforce self referential integrity. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What are the min.extents allocated to a rollback extent ? Answer: Two ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What are the states of a rollback segment ? What is the difference between partl y available and needs recovery ? Answer: The various states of a rollback segment are : ONLINE OFFLINE PARTLY AVAILABLE NEEDS RECOVERY INVALID. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What is the difference between unique key and primary key ? Answer: Unique key can be null; Primary key cannot be null. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------An insert statement followed by a create table statement followed by rollback ? Will the rows be inserted ? Answer: No. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Can you define multiple savepoints ? Answer: Yes. ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Can you Rollback to any savepoint ? Answer: Yes. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What is the maximum no.of columns a table can have ? Answer: 254. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What is the significance of the & and && operators in PL SQL ? Answer: The & operator means that the PL SQL block requires user input for a var iable.The && operator means that the value of this variable should be the same a s inputted by the user previously for this same variable ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Can you pass a parameter to a cursor ? Answer: Explicit cursors can take parameters, as the example below shows.A curso r parameter can appear in a query wherever a constant can appear. CURSOR c1 (median IN NUMBER) IS SELECT job, ename FROM emp WHERE sal > median; ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What are the various types of RollBack Segments ? Answer: The types of Rollback sagments are as follows : Public Available to all instances Private Available to specific instance ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Can you use %RowCount as a parameter to a cursor ? Answer: Yes ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Is the query below allowed : Select sal, ename Into x From emp Where ename = KING (Where x is a record of N umber(4) and Char(15)) Answer: Yes ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Is the assignment given below allowed : ABC = PQR (Where ABC and PQR are records) Answer: Yes ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Is this for loop allowed : For x in &Start..&End Loop Answer: Yes ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------How many rows will the following SQL return : Select * from emp Where rownum < 1 0; Answer: 9 rows ---------------------------------------------------------------------------------------------------------------------------------------------------------------

-------------------------------------------How many rows will the following SQL return : Select * from emp Where rownum = 1 0; Answer: No rows ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Which symbol preceeds the path to the table in the remote database ? Answer: @ ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Are views automatically updated when base tables are updated ? Answer: Yes ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Can a trigger written for a view ? Answer: No ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------If all the values from a cursor have been fetched and another fetch is issued, t he output will be : error, last record or first record ? Answer: Last Record ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------A table has the following data : [[5, Null, 10]].What will the average function return ? Answer: 7.5 ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Is Sysdate a system variable or a system function? Answer: System Function ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Consider a sequence whose currval is 1 and gets incremented by 1 by using the ne xtval reference we get the next number 2.Suppose at this point we issue an rollb ack and again issue a nextval.What will the output be ? Answer: 3 ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Definition of relational DataBase by Dr.Codd (IBM)? Answer: A Relational Database is a database where all data visible to the user i s organized strictly as tables of data values and where all database operations work on these tables. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What is Multi Threaded Server (MTA) ? Answer: In a Single Threaded Architecture (or a dedicated server configuration) the database manager creates a separate process for each database user.But in MT A the database manager can assign multiple users (multiple user processes) to a single dispatcher (server process), a controlling process that queues request fo r work thus reducing the databases memory requirement and resources. --------------------------------------------------------------------------------

--------------------------------------------------------------------------------------------------------------------------Which are initial RDBMS, Hierarchical & N/w database ? Answer: RDBMS - R system Hierarchical - IMS N/W - DBTG ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Difference between Oracle 6 and Oracle 7 Answer: 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 Roll back Size Adjustment No provision Truncate command No provision Distributed Database Distributed Query Table replication & snapshots No provision Client/Server Tech No provision ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What is Functional Dependency? Answer: Given a relation R, attribute Y of R is functionally dependent on attrib ute X of R if and only if each X-value has associated with it precisely one -Y v alue in R ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What is Auditing ? Answer: 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 ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------While designing in client/server what are the 2 imp.things to be considered ? Answer: Network Overhead (traffic), Speed and Load of client server ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What are the disadvantages of SQL ? Answer: 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 ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------When to create indexes ? Answer: To be created when table is queried for less than 2% or 4% to 25% of the table rows. ---------------------------------------------------------------------------------------------------------------------------------------------------------------

-------------------------------------------How can you avoid indexes ? Answer: To make index access path unavailable Use FULL hint to optimizer for ful l 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. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What is the result of the following SQL : Select 1 from dual UNION Select A fr om dual; Answer: Error ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Can database trigger written on synonym of a table and if it can be then what wo uld be the effect if srcinal table is accessed. Answer: Yes, database trigger would fire. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Can you alter synonym of view or view ? Answer: No ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Can you create index on view Answer: No. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What is the difference between a view and a synonym ? Answer: Synonym is just a second name of table used for multiple link of databas e.View can be created with many tables, and with virtual columns and with condit ions.But synonym can be on view. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What s the length of SQL integer ? Answer: 32 bit length ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What is the difference between foreign key and reference key ? Answer: Foreign key is the key i.e.attribute which refers to another table prima ry key. Reference key is the primary key of table referred by another table. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Can dual table be deleted, dropped or altered or updated or inserted ? Answer: Yes ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------If content of dual is updated to some value computation takes place or not ? Answer: Yes ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------If any other table same as dual is created would it act similar to dual?

Answer: Yes ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------For which relational operators in where clause, index is not used ? Answer: , like %... is NOT functions, field +constant, field|| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Assume that there are multiple databases running on one machine.How can you swit ch from one to another ? Answer: Changing the ORACLE_SID ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------What are the advantages of Oracle ? Answer: Portability : Oracle is ported to more platforms than any of its competi tors, running on more than 100 hardware platforms and 20 networking protocols. M arket 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 t hat 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 indu strial 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 larg e databases.Oracle can manage > 100GB databases. Multiple database support : Ora cle has a superior ability to manage multiple databases within the same transact ion using a two-phase commit protocol. ----------+---------------+---------------+---------------+---------------+--------------+---------------+---------------+---------------+---------------+-------------What is a forward declaration ? What is its use ? Answer: PL/SQL requires that you declare an identifier before using it.Therefore , you must declare 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. ----------+---------------+---------------+---------------+---------------+--------------+---------------+---------------+---------------+---------------+-------------What are actual and formal parameters ? Answer: Actual Parameters : Subprograms pass information using parameters.The va riables or expressions referenced in the parameter list of a subprogram call are actual parameters.For example, the following procedure call lists two actual pa rameters 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 param eters.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 ; ----------+---------------+---------------+---------------+---------------+--------------+---------------+---------------+---------------+---------------+-------------What are the types of Notation ? Answer: Position, Named, Mixed and Restrictions. ----------+---------------+---------------+---------------+---------------+--------------+---------------+---------------+---------------+---------------+--------------

What all important parameters of the init.ora are supposed to be increased if yo u want to increase the SGA size ? Answer: In our case, db_block_buffers was changed from 60 to 1000 (std values ar e 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 & 30 0) db_block_size was changed from 2048 (2K) to 4096 (4K) {at the time of databas e 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. ----------+---------------+---------------+---------------+---------------+--------------+---------------+---------------+---------------+---------------+-------------If I have an execute privilege on a procedure in another users schema, can I exe cute his procedure even though I do not have privileges on the tables within the procedure ? Answer: Yes ----------+---------------+---------------+---------------+---------------+--------------+---------------+---------------+---------------+---------------+-------------What are various types of joins ? Answer: Types of joins are: Equijoins Non-equijoins self join outer join ----------+---------------+---------------+---------------+---------------+--------------+---------------+---------------+---------------+---------------+-------------What is a package cursor ? Answer: A package cursor is a cursor which you declare in the package specificat ion without an SQL statement.The SQL statement for the cursor is attached dynami cally at runtime from calling procedures. ----------+---------------+---------------+---------------+---------------+--------------+---------------+---------------+---------------+---------------+-------------If you insert a row in a table, then create another table and then say Rollback. In this case will the row be inserted ? Answer: 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 fai ls internally (eg table already exists error) and not syntactically. ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++++++++ What is the purpose of the PL/SQL language? PL/SQL is an extension of SQL. SQL is non-procedural. PL/SQL is a procedural lan guage designed by oracle to overcome the limitations that exist in SQL. Say True or False. If False, explain why. Routines written in PL/SQL can be called in Oracle call interface, Java, Pro*C/C ++, COBOL etc. True. Say True or False. If False, explain why. PL/SQL does not have data types or variables. False. PL/SQL has all features of a structured programming language including da ta types, variables, subroutines, modules and procedural constructs. State few notable characteristics of PL/SQL. Block-structured language.

Stored procedures help better sharing of application. Portable to all environments that support Oracle. Integration with the Oracle data dictionary. ---Name few schema objects that can be created using PL/SQL? Stored procedures and functions Packages Triggers Cursors ------------State some features or programming constructs supported by PL/SQL? Variables and constants Embedded SQL support Flow control Cursor management Exception handling Stored procedures and packages Triggers ----------------------------What are the three basic sections of a PL/SQL block? Declaration section Execution section Exception section --------------What is wrong in the following assignment statement? balance = balance + 2000; Use of wrong assignment operator. The correct syntax is: balance := balance + 20 00; ---------------Write a single statement that concatenates the words `Hello' and `World' and assign it i n a variable named greeting.? greeting := `Hello' || `World'; ---------------------------Which operator has the highest precedence among the following AND, NOT, OR? NOT Which of the following operator has the lowest precedence among the following **, OR, NULL ? OR What does the colon sign (: ) implies in the following statement? :deficit := balance ± loan; The colon (: )sign implies that the variable :deficit is an external variable. What is the purpose of %type data type? Explain with example. It assigns a variable the same data type used by the column, for which the varia ble is created. For example,

dcode := dept.detpno%type; The variable dcode is created with the same data type as that of the deptno colu mn of the dept table. What is the purpose of %rowtype data type? Explain with example. It declares a composed variable that is equivalent to the row of a table. After the variable is created, the fields of the table can be accessed, using the name of this variable. For example emptype := emp%rowtype; name := emptype.empname; What is a PL/SQL package? A package is a file that groups functions, cursors, stored procedures, and varia bles in one place.

What is a trigger? A trigger is a PL/SQL program that is stored in the database and executed immedi ately before or after the INSERT, UPDATE, and DELETE commands.

What are the PL/SQL cursors? Oracle uses workspaces to execute the SQL commands. In other words, when Oracle processes a SQL command, it opens an area in the memory called Private SQL Area. A cursor is an identifier for this area. It allows programmers to name this are a and access it's information.

Say True or False. If False, explain why. PL/SQL engine is part of Oracle Server. True. Say True or False. If False, explain why. The BEGIN declaration starts the variable declaration sections of a PL/SQL block . False. The BEGIN declaration starts the execution section. Say True or False. If False, explain why. The PL/SQL engine executes the procedural commands and passes the SQL commands f or the Oracle server to process. True. Say True or False. If False, explain why. PL/SQL supports the CREATE command. False. PL/SQL doesn't support the data definition commands like CREATE.

What is returned by the cursor attribute SQL%ROWCOUNT? It returns the number of rows that are processed by a SQL statement.

What is returned by the cursor attribute SQL%FOUND? It returns the Boolean value TRUE if at least one row was processed. What is returned by the cursor attribute SQL%NOTFOUND? It returns the Boolean value TRUE if no rows were processed. Which command/commands allow iteration a use of loops in a PL/SQL block? LOOP command, FOR.. LOOP command, WHILE command. What is the difference in execution of triggers and stored procedures? A trigger is automatically executed without any action required by the user, whe reas, a stored procedure needs to be explicitly invoked.

What are the uses of triggers? Basically triggers are used to create consistencies, access restriction and impl ement securities to the database. Triggers are also used for Creating validation mechanisms involving searches in multiple tables Creating logs to register the use of a table Update other tables as a result of inclusion or changes in the current table.

Say True or False. If False, explain why. Triggers can be associated to a view. True. Say True or False. If False, explain why. When a trigger is associated to a view, the base table triggers are normally dis abled. False. When a trigger is associated to a view, the base table triggers are norma lly enabled.

Say True or False. If False, explain why. A trigger can perform the role of a constraint, forcing an integrity rule. True. Say True or False. If False, explain why. A trigger can execute the COMMIT, ROLLBACK, or SAVEPOINT commands. A trigger cannot execute the COMMIT, ROLLBACK, or SAVEPOINT commands. What is the use of a WHEN clause in a trigger? A WHEN clause specifies the condition that must be true for the trigger to be tr iggered. Say True or False. If False, explain why. Statement level triggers are triggered only once. True.

What is the purpose of the optional argument [OR REPLACE] in a CREATE TRIGGER co mmand? The optional argument [OR REPLACE] in a CREATE TRIGGER command re creates an exi sting trigger. Using this option allows changing the definition of an existing t rigger without having to delete it first. Say True or False. If False, explain why. INSTEAD OF is a valid option only for triggers in a table. False. INSTEAD OF is a valid option only for views. INSTEAD OF trigger cannot be specified in a table. Write a statement to disable a trigger named update_marks. ALTER TRIGGER update_marks DISABLE;

Which command is used to delete a trigger? DROP TRIGGER command. Which command is used to delete a procedure? DROP PROCEDURE command. .

What is the difference between a function and a stored procedure? A function returns a value and a stored procedure doesn't return a value.

How do you declare a user defined exception? User defined exceptions are declared under the DECLARE section, with the keyword EXCEPTION. Syntax EXCEPTION; What do you understand by explicit cursors? Explicit cursors are defined explicitly using the CURSOR statement, with a gener al syntax CURSOR cursor_name [(parameters)] IS query_expression; It allows processing queries that return multiple rows.

What are the steps that need to be performed to use an explicit cursor? Discuss briefly. The steps that need to be performed on explicit cursor are DECLARE - assigns a name to the cursor and defines the structure of query within i t. OPEN - executes the query, whereby the rows returned by the query are available fo

r fetching. FETCH - assigns values from the current row (cursor position) into specified varia bles. CLOSE - releases the memory space.

PL/SQL packages usually have two parts. What are these two parts? PL/SQL packages have two parts Specification part - where the interface to the application are defined. Body part - where the implementation of the specification are defined.

Which command(s) are used for creating PL/SQL packages? CREATE PACKAGE command is used for creating the specification part. CREATE PACKA GE BODY command is used for creating the body part.

How do you refer to the types, objects and subprograms declared within a packag e? The types, objects, and subprograms declared within a package are referred to u sing the dot notation as package_name.type_name package_name.object_name package_name.subprogram_name Say True or False. If False, explain why. PL/SQL allows subprogram overloading feature within a package. true

Which command is used to delete a package? The DROP PACKAGE command. What is the difference between implicit and explicit cursors? Oracle implicitly declares a cursor to all the DDL and DML commands that return only one row. For queries returning multiple rows, an explicit cursor is created .

Say True or False. If False, explain why.

The %NOTFOUND attribute returns true when the cursor is not created explicitly. False. The %NOTFOUND attribute returns true when the last row of the cursor is p rocessed and no other row is available. Say True or False. If False, explain why. The %ROWCOUNT attribute returns the total number of rows returned by the FETCH c ommand. True.

Oracle interview questions and answers

Part 2 | Part 3 | Part 4 | Part 5 | Part 6 | Part 7 | Part 8 | Part 9 Oracle interview questions

April 17, 2013 at 01:16 PM by Kshipra Singh

1. Explain: a.) Integrity Constraints It can be called as a declarative way in order to define a business rule for a t able s column b.) Index It can be called as an optional structure which is associated with a table for direct access to the rows Index can be created for one or more columns in a table c.) Extent It can be defined as a specific number of contiguous data blocks in single all ocation. It is used to store a specific type of information. 2. What is ANALYZE command used for? ANALYZE command is used to perform various functions on index, table, or cluster , as listed below: It helps in dentifying migrated and chained rows of the table or cluster. It helps in validating the structure of the object. It helps in collecting the statistics about object used by the optimizer. They are then stored in the data dictionary. It helps in deleting statistics used by object from the data dictionary. Oracle 11g dba interview questions and answers

50 questions

Test your Oracle skills: Oracle Oracle Oracle Oracle Oracle Oracle

interview test part 1 (40 questions) DBA interview test (30 questions) PLSQL interview test (30 questions) Replication interview test (20 questions) Architecture interview test (20 questions) Transaction interview test (20 questions)

3. a.) List the types of joins used in writing SUBQUERIES.

Self join Outer Join Equi join b.) List the various Oracle database objects. TABLES VIEWS INDEXES SYNONYMS SEQUENCES TABLESPACES 4. a.) Explain i.)Rename ii.)Alias. Rename It is a permanent name provided to a table or column. Alias It is a temporary name provided to a table or column which gets over a fter the execution of SQL statement. b.) What is a view? It is virtual table which is defined as a stored procedure based on one or mor e tables. 5. a.) What are the varoius components of physical database structure of Oracle database? Oracle database comprises of three kinds of files: Datafiles, Redo log files, Control files. b.) List out the components of logical database structure of Oracle database. Tablespaces Database s schema objects. 6. a.) What do you mean by a tablespace? These are the Logical Storage Units into which a database is divided. It is used to group together the related logical structures. b.) What is Control File used for? Control File is used for: Database recovery. Whenever an instance of an ORACLE database begins, its control file is used to identify the database and redo log files that must be opened for database opera tion to go ahead. 7. a.) What is a synonym? What are its various types? A synonym can be called as an alias for a table, view, sequence or program unit. It is basically of two types: Private Only the owner can access it. Public Can be accessed by any database user. b.) What are the uses of synonyms?

Mask the real name and owner of an object. Provide public access to an object Provide location transparency for tables, views or program units of a remote d atabase. Simplify the SQL statements for database users. 8.) What do you mean by a deadlock? When two processes are waiting to update the rows of a table which are locked by another process, the situation is called a deadlock. The reasons for it to happen are: lack of proper row lock commands. Poor design of front end application It reduces the performance of the server severely. These locks get automatically released automatically when a commit/rollback op eration is performed or any process is killed externally. 9.) a.) What suggestions do you have to reduce the network traffic? Following are some of the actions which can be taken to reduce the network traff ic: Use snapshots to replicate data. Use remote procedure calls. Replicate data in distributed environment. b.) What are the various types of snapshots ? There are two types of snapshots: Simple snapshots Based on a query that does not contain GROUP BY clauses, CO NNECT BY clauses, JOINs, sub query or snashot of operations. Complex snapshots which contains atleast any one of the above. 10.) What is a sub query? What are its various types? Sub Query also termed as Nested Query or Inner Query is used to get data from multiple tables. A sub query is added in the where clause of the main query. There can be two types of subqueries: a.) Correlated sub query It can reference column in a table listed in the from list of the outer query but is not as independent as a query. . b.) Non Correlated sub query Results of this sub query are submitted to the main query or parent query. It is independent like a query 11.) Will you be able to store pictures in the database?Explain. Yes, pictures can be stored in the database using Long Raw Data type. This datatype is used to store binary data for 2 gigabytes of length. However, the table can have only one Long Raw data type. 12.) Explain: a.) Integrity constraint. It is a declaration defined in a business rule for a table column. Integrity constraint ensures the accuracy and consistency of data in a databas

e. It is of three types main Integrity.

namely

Domain Integrity, Referential Integrity and Do

b.) COALESCE function This function is used to return the value which is set not to be null in the l ist. Incase all values in the list are null the coalesce function will return NULL. Its representation: Coalesce(value1, value2, value3,¼) 13.) Explain the following: a.) BLOB datatype. It is a data type with varying length binary string, used to store two gigabyt es memory. For BLOB, the length needs to be specified in bytes. b.) DML. DML it is also termed as Data Manipulation Language (DML). It is used to access and manipulate data in the existing objects. DML statements are insert, select, update and delete. 14.) Differentiate between: a.) TRANSLATE and REPLACE. Translate is used to substitute character by character. Replace is used to substitute a single character with a word. b.) What is Merge Statement used for? Merge statement is used to select rows from one or more data source to updatin g and insert into a table or a view. 15.) What are the various Oracle Database objects? Various database objects are as follows: Tables ± This is a set of elements organized in vertical and horizontal fashion. Tablespaces ± This is a logical storage unit in Oracle. Views ± It is virtual table derived from one or more tables. Indexes ± This is a performance tuning method to process the records. Synonyms ± This is a name for tables. Sequences. 16. What is the purpose of Save Points in Oracle database? Save Points are used to divide a transaction into smaller phases. It enables rolling back part of a transaction. Maximum 5 save points are allowed in Oracle Database. Whenever an error is encountered, it is possible to rollback from the point wh ere the SAVEPOINT has been saved. 17. a.) What is an ALERT? It a window which appears on the screen overlaying a portion of the current di splay. b.) Differentiate between post database commit and post form commit.

The post database commit trigger is fired after oracle forms issue the commit to finalized transactions. The post form commit is fired during the post and commit transactions process, after the database commit occurs. 18. Differentiate between pre select and pre query. Once oracle forms construct the select statement to be issued Pre select is fi red during the execute query and count query processing. All this happens before the statement is actually issued. The pre query trigger is fired just before oracle forms issue the select state ment to the database. 19. What is hot backup and logical backup? Hot backup Backing up the archive log files when database is open is called Hot backup. To do this, the ARCHIVELOG mode is enabled. Following files are backed up All data files, Archive log, redo log files an d control files. Logical backup Logical back ip is reading a set of database records and writing them into a f ile. An Export utility is required to take the backup while an Import utility is re quired to recover from the backup. 20. What do you mean by Redo Log file mirroring ? The process of having a copy of redo log files is called mirroring. It is done by creating group of log files together. This ensures that LGWR aut omatically writes them to all the members of the current on line redo log group. In case a group fails, the database automatically switches over to the next gr oup. It diminishes the performance. Interview Questions Oracle interview questions | part 8 | part 9

Part 2

Part 1 | Part 2 | Part 3 | Part 4 | part 5 | part 6 | part 7

What is implicit cursor in Oracle? Latest answer: An implicit cursor is a cursor which is internally created by Ora cle, It is created by Oracle for each individual SQL........... Read answer Can you pass a parameter to a cursor? Explain with an explain Latest answer: Yes, explicit cursors can take parameters........... Read answer What is a package cursor? Latest answer: In a package cursor, the SQL statement for the cursor is attached dynamically at runtime from calling procedures............

Read answer Explain why cursor variables are easier to use than cursors. Latest answer: They are easier to define as there is no need to specify a query statement, The query can also be specified dynamically at the opening time...... ..... Read answer What is locking, advantages of locking and types of locking in oracle? Latest answer: Locking protect table when several users are accessing the same t able. Locking is a concurrency control technique in oracle. It helps in data int egrity while allowing maximum.......... Read answer What are transaction isolation levels supported by Oracle? Latest answer: READ COMMITTED: If row locks are obtained by a certain transactio n, then any other transaction that contains DML needs to wait until the row lock s have been released by that particular transaction............. Read answer Explain how to view existing locks on the database. Latest answer: A number of data locks need to be monitored, in order to maintain a good performance level for all sessions, along with the time for which they l ast............ Read answer Explain how to lock and unlock a user account in Oracle. Latest answer: SQL> ALTER USER user_name ACCOUNT LOCK; SQL> ALTER USER user_name ACCOUNT UNLOCK; Read answer What are background processes in oracle? Latest answer: Oracle uses background process to increase performance : Database writer, DBWn, Log Writer, LGWR, Checkpoint, CKPT, System Monitor, SMON, Process Monitor, PMON, Archiver, ARCn........... Read answer What is SQL*Loader? Latest answer: It is a database tool that allows data to be loaded from external files into database tables, It is available as part of the free Oracle 10g Expr ession Edition.......... Read answer What is a SQL*Loader Control File? Latest answer: A SQL*Loader control file contains the following specification: l ocation of the input data file, format of the input date file, target table wher e the data should be loaded............ Read answer Explain oracle memory structures. Latest answer: Two memory area: System global area(SGA), Program Global Area(PGA

).......... Read answer What is Program Global Area (PGA)? Latest answer: The PGA is a memory area that contains data and control informati on for the Oracle server processes. This area consists of the following componen ts:............. Read answer What is a shared pool? Latest answer: It is the area in SGA that allows sharing of parsed SQL statement s among concurrent users........... Read answer What is snapshot in oracle? Latest answer: A recent copy of a table or a subset of rows or cols of a table i s called as snapshot in oracle. A snapshot is more useful in distributed computi ng environment. We can create.......... Read answer What is a synonym? Latest answer: Synonym simplifies the use of the table, the table for which syno nym is created can be referred by synonym name............ Read answer What is a schema? Latest answer: Schema represents structure of the database. Database has two mai n types of schemas partitioned : Physical schema: Describes the database design at the physical level............. Read answer Explain how to list all indexes in your schema. Latest answer: The list of all indexes in a schema can be obtained through the U SER_INDEXES view with a SELECT statement:........... Read answer What are Schema Objects? Latest answer: Schema objects are the logical database structure that represents database s data. Schema objects include tables, views, sequences, synonyms, ind exes, clusters, database............ Read answer What is an Archiver? Latest answer: Archiving is the process of removing of old data and unused data from the main databases. This process keeps databases smaller, more manageable a nd thus acquires............. Read answer What is a sequence in oracle? Latest answer: A Sequence is a user created database object. A sequence can be s hared by multiple users to generate unique integers. This object is used to crea

te a primary key value............... Read answer Difference between a hot backup and a cold backup Latest answer: Cold Backup : In this type of backup, after the database is shut down, DBA exits the SVRMGR utility and copies the log files, data files and cont rol files onto a backup media........... Read answer How to retrieve 5th highest sal from emp table? SELECT DISTINCT (emp1.sal) FROM EMP emp1 WHERE &N = (SELECT COUNT (DISTINCT (emp 2.sal)).......... Read answer What is $FLEX$ and $PROFILES$? Where are they used? $FLEX$ is used to get a value used in the previous value set. It is usually used to retrieve the Flex value contained in an AOL value.......... Read answer How to call a trigger inside a stored procedure? A trigger cannot be called within a stored procedure. Triggers are executed auto matically as a result of DML or DDl commands............ Read answer What is WATER MARK IN oracle? Explain the significance of High water mark. WATER MARK is a divided segment of used and free blocks. Blocks which are below high WATER MARK i.e. used blocks, have at least once........... Read answer What is an object groups? Object group is a container for a group of objects.......... Read answer Difference between clustering and mirroring Clustering means one than one database server configured for the same user conne ction. When users connect, one of the server's responds.......... Read answer Difference between paging and fragmentation Paging is a concept occurring in memory, whereas, Fragmentation occurs on disk l evel.......... Read answer Can you explain how to insert an image in table in oracle? Insert image into a table: Create the following table: create table pics_table ( bfile_id number,......... Read answer How to find out second largest value in the table? SELECT * FROM EMP WHERE SAL IN (SELECT MAX(SAL) FROM EMP.........

Read answer Disadvantage of user defined function in oracle. Disadvantage of UDF in Oracle: Oracle does not support calling UDFs with Boolean parameters or return types.......... Read answer Explain the significance of cluster table or non cluster table. A Cluster provides an alternate method of storing table data. It is made up of a group of tables that share the same data......... Read answer What are the purposes of Import and Export utilities? Latest answer: Import and Export utilities are helpful in following ways: They c an be used for backup and recovery process, they can also be used while moving d atabase between two different............... Read answer Difference between ARCHIVELOG mode and NOARCHIVELOG mode Latest answer: There are two modes in which the hot backup works: ARCHIEVELOG mo de, NOARCHIVELOG mode........ Read answer What are the srcinal Export and Import Utilities? Latest answer: The import and export utilities of oracle provide a very simple w ay to transfer data objects between Oracle databases. These may reside on hetero geneous software and hardware............ Read answer What are data pump Export and Import Modes? Latest answer: Data pump export and import modes are used to determine the type and portions of database to be exported and imported:............... Read answer What are SQLCODE and SQLERRM and why are they important for PL/SQL developers? Latest answer: When a SQL statement raises an exception, Oracle captures the err or codes by using the SQLCODE and SQLERRM globally defined variables............ ... Read answer Explain user defined exceptions in oracle. Explain the concepts of Exception in Oracle. Explain its type. Latest answer: Exceptions in oracle occur when unwanted situations happen during the execution of a program. They can occur due to system error, user error or a pplication error............. Read answer How exceptions are raised in oracle? Latest answer: Internal exceptions are raised implicitly by the run time system. However, user defined exceptions must be raised explicitly by RAISE statements.

............... Read answer What is tkprof and how is it used? Latest answer: Tkprof is a performance diagnosing utility available to DBAs. It formats a trace file into a more readable format for performance analysis. So th at the DBA can identify and resolve............... Read answer What is Oracle Server Autotrace? Latest answer: The Autotrace feature of Oracle server generates two statement ex ecution reports which are useful for performance tuning. They are: Statement exe cution path.............. Read answer Explain the different types of queries in Oracle. Latest answer: Session Queries are implicitly constructed and executed by a Sess ion based on input parameters.Input parameters are used to perform the most comm on data source actions on objects............ Read answer What is SQL*Plus? Latest answer: SQL*Plus is an interactive and batch query tool, it gets installe d with every Oracle Database Server or Client installation............. Read answer Explain how to change SQL*Plus system settings. Latest answer: The SET command can be used to change the settings in the SQl*PLU S environment : SET AUTOCOMMIT OFF: Turns off the auto commit feature, SET FEEDB ACK OFF............ Read answer What are SQL*Plus Environment variables? Latest answer: The behaviour of SQL PLUS depends on some environmental variables predefined in the OS: ORACLE_HOME: This variable stores the home directory wher e the Oracle client............. Read answer What is Output Spooling in SQL*Plus? Latest answer: The spooling feature facilitates copying of all the contents of t he command line SQL*Plus to a specified file. This feature is called Spooling... ......... Read answer What is Input Buffer in SQL*Plus? Latest answer: Input buffer feature of the command line SQL*Plus tool allows a r evision of multiple line command and rerunning it with a couple of simple comman ds. The last SQL statement is........... Read answer What is a subquery in Oracle?

Latest answer: When a query needs to be run which has a condition that needs to be a result of another query then, the query in the condition part of the main o ne is called a sub query............... Read answer What is Data Block? Latest answer: Data blocks are also called logical blocks, Oracle blocks, or pag es. At the finest level of granularity, Oracle stores data in data blocks....... ..... Read answer Explain the difference between a data block, an extent and a segment. Latest answer: A data block is the smallest unit of logical storage for a databa se object. As objects grow they take chunks of additional storage that are compo sed of contiguous data blocks............. Read answer What are the uses of Rollback Segment? Latest answer: Rollback segments undo changes when a transaction is rolled back, they also ensure that transactions leave the uncommitted changes unnoticed..... ......... Read answer What is Rollback Segment in oracle? Latest answer: Rollback Segment in oracle is used to store "undo" information te mporarily......... Read answer What are the different types of Segments? Latest answer: Data Segment, Index Segment, Rollback Segment, and Temporary Segm ent........... Read answer Explain difference between SQL and PL/SQL. Latest answer: PL/SQL is a transaction processing language that offers the follo wing advantages: support for SQL SQL is flexible, powerful and easy to learn. support for object oriented programming............... Read answer Part 1 | Part 2 | P

Interview Questions Oracle interview questions | part 8 | part 9

Part 3

Part 1 | Part 2 | Part 3 | Part 4 | part 5 | part 6 | part 7

Write a PL/SQL program for a function returning total tax collected from a parti cular place. Latest answer: PL/SQL program

Create of Replace Function Tax Amt Place varchar2, Return Number is............ Read answer What are the types PL/SQL code blocks? Latest answer: Anonymous Block, Stored Program Unit, Trigger........... Read answer Advantages of PL/SQL Latest answer: Support SQL data manipulation, provide facilities like conditiona l checking, branching and looping............. Read answer What is WebDB? Latest answer: WebDB is a tool written in PL/SQL, used to develop HTML based app lication that can easily interact with Oracle data................... Read answer What is Nested Table? Latest answer: Nested Table is a table inside a table. It can have several rows for each row of its parent table............ Read answer What is clusters? Latest answer: Clusters group together tables that share common columns. These t ables are often used together......... Read answer Explain how to add a new column to an existing Table in Oracle. Latest answer: Use the ALTER TABLE command to do this ALTER TABLE employee ADD ( department VARCHAR2);......... Read answer How many types of Tables supported by Oracle? Explain them Latest answer: Ordinary (heap organized) table, Clustered table, Index organized table, Partitioned table........... Read answer Explain how to view all columns in an Existing Table. Latest answer: Use the command DESC and the table name to view the information a bout the columns.......... Read answer Explain how to recover a dropped Table in Oracle. Latest answer: select * from recyclebin where srcinal_name =

table_name ;

Then u can use flashback table table_name to before drop;..................... Read answer

What is an Oracle Recycle Bin? Latest answer: The tables that have been dropped can be retrieved back using the reycle bin feature of Oracle, they can be recovered back by the Flashback Drop action............ Read answer What is an External Table? Latest answer: A table with its data stored outside the database as an OS file i s an external table........... Read answer Describe how to load data through External Tables. Latest answer: Create an external table with columns matching data fields in the external file........... Read answer What is the role of Archiver [ARCn]? ARCn is an oracle background process responsible for copying the entirely filled online redo log file to the archive log......... Read answer Structural difference between bitmap and btree index in oracle. Btree It is made of branch nodes and leaf nodes. Branch nodes holds prefix key v alue along with the link to the leaf node. The leaf node in turn........ Read answer Can you explain how to convert oracle table data into excel sheet? There are 2 ways to do so: 1. Simply use the migration wizard shipped with Oracl e......... Read answer When should we go for hash partitioning? Scenarios for choosing hash partitioning: Not enough knowledge about how much da ta maps into a give range........... Read answer What is Materialized view? What is a snapshot? What are the similarities and dif ferences between Materialized views and snapshots? A materialized view is a database object that contains the results of a query. A snapshot is similar to materialized view.......... Read answer What are the advantages of running a database in NO archive log mode? 1. Less disk space is consumed 2. Causes database to freeze if disk gets full... ..... Read answer What are the advantages of running a database in archive log mode? It makes it possible to recover database even in case of disk failure...........

. Read answer What is dba_segment in oracle? DBA_SEGMENTS tells about the space allocated for all segments in the database fo r storage......... Read answer ) What is oracle database ? Oracle Database is a relational database management system (RDBMS) which is used to store and retrieve the large amounts of data. Oracle Database had physical a nd logical structures. Logical structures and physical structures are separated from each other

2) What is schema? A user account and its associated data including tables, views, indexes, cluster s, sequences,procedures, functions, triggers,packages and database links is know n as Oracle schema. System, SCOTT etc are default schema s. We can create a new Schema/User. But we can t drop default database schema s.

3) What is a Tablespace? Oracle use Tablespace for logical data Storage. Physically, data will get stored in Datafiles. Datafiles will be connected to tablespace. A tablespace can have multiple datafiles. A tablespace can have objects from different schema s and a schema can have multiple tablespace s. Database creates "SYSTEM tablespace" by d efault during database creation. It contains read only data dictionary tables wh ich contains the information about the database. Also Read Basic to Advanced Oracle SQL Query Interview Question and Answers 4) What is a Control file redo files, ile database

Control File ? is a binary file which stores Database name, associated data files, DB creation time and current log sequence number. Without control f cannot be started and can hamper data recovery.

5) Define data blocks ? Data Blocks are the base unit of logical database space. Each data block represe nts a specific number of bytes of database space on a disk 6) What is an Extent ? Extent is a collection of Continuous data blocks, which is used for storing a sp ecific type of information. Are you looking for frequently asked Database Interview Questions and Answers? C lick here 7) What is a Segment ? A segment is a collection of extends which is used for storing a specific data s tructure and resides in the same tablespace. 8) What is Rollback Segment ? Database contain one or more Rollback Segments to roll back transactions and dat a recovery.

9) What are the different type of Segments ? Data Segment(for storing User Data), Index Segment (for storing index), Rollback Segment and Temporary Segment. 10) What is a Redo Log ? Redo Log files is a collection of 2 or more pre allocated files, which is used i n data recovery. When ever a change is made to the database, change info gets st ored in redo files. In case of a database crash, we can used redo files for data recovery. 11) What is a table Cluster ? Table Cluster is a group of related tables that share common columns are store r elated data in the same block.

Write a PL/SQL program for a trigger. PL/SQL program for tracking operation on a emp table. Create or Replace Trigger EmpTracking Before Insert or Delete or Update on Emp For each row Declare Begin If Inserting then /*Can perform operations just before record is inserted into the emp table*/ Else if Updating then /*Can perform operations just before record is about to be updated */ Else if Deleting then /*Can perform operations just before record is about to be delete d*/ End If End EmpTracking

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF