127
SQL COMMANDS 1).Select those employees who comm is null. A. select * from emp where comm is null; 2) Select list of managers and corresponding Clerks. A. select a.ename "Manager" , b.ename "Clerk" from emp a, emp b where b.mgr= a.empno; 3) Select list of employee name with their deptno,dname and loc. A. select empno,emp.deptno,dname,loc from emp,dept where emp.deptno= dept.deptno 4) Select 2nd maximum salary from emp table. A. select max(sal) from emp where sal<(select max(sal) from emp); 5) Select 5th maximum salary A. select max(sal) from emp a where 5 =(select count(*) from emp b where a.sal< b.sal); 6) Select Alternate Rows from a table. For Odd Rows: A. select * from emp where mod(ascii(substr(rowid,18)),2)=0 For Even Rows: A. select * from emp where mod(ascii(substr(rowid,18)),2)=1 7) How do I get a random number in Oracle query. A. select dbms_random.random from dual; 8) To Select Least ,Greatest Numbers. A. select least(1,2) from dual select greatest(1,2) from dual select greatest(1.2,2.3) from dual select least(1.2,2.3) from dual 9) To Round a number. A. select ceil(1208917.97802706) from dual; 10) To Truncate a number. A. select floor(1208917.97802706) from dual; 11) Select employees who joined before their manager. A. select a.empno,a.ename from emp a, emp b where a.mgr=b.empno and a.hiredate< b.hiredate; 11) To Select Only Characters from a combination of numbers and characters. select translate ('RAGHU40020','ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ') FROM dual; 12) To get those employee whose name ends with 'RD' : select * from emp where ename like '%RD'; 13) To select those , whose last names are a phonetic representation of 'SMYTHE' : select * from emp where soundex(ename)=soundex('SMYTHE') To select those , whose job is phonetic representation of 'SALESMEN' : select * from emp where soundex(job)=soundex('SALESMEN'); 14) To display employee details of workers who joined before their managers : select a.ename from emp a, emp b where a.mgr=b.empno and a.hiredate<b.hiredate; 15) Display the names of employees whose sal is greater than max sal of sales :

Complete SQL Commands

Embed Size (px)

DESCRIPTION

Complete Set of SQL Commands

Citation preview

Page 1: Complete SQL Commands

SQL COMMANDS1).Select those employees who comm is null.A. select * from emp where comm is null;2) Select list of managers and corresponding Clerks.A. select a.ename "Manager" , b.ename "Clerk" from emp a, emp b where b.mgr=a.empno;3) Select list of employee name with their deptno,dname and loc.A. select empno,emp.deptno,dname,loc from emp,dept where emp.deptno=dept.deptno4) Select 2nd maximum salary from emp table.A. select max(sal) from emp where sal<(select max(sal) from emp);5) Select 5th maximum salaryA. select max(sal) from emp a where 5 =(select count(*) from emp b where a.sal< b.sal);6) Select Alternate Rows from a table.For Odd Rows:A. select * from emp where mod(ascii(substr(rowid,18)),2)=0For Even Rows:A. select * from emp where mod(ascii(substr(rowid,18)),2)=17) How do I get a random number in Oracle query.A. select dbms_random.random from dual;8) To Select Least ,Greatest Numbers.A. select least(1,2) from dualselect greatest(1,2) from dualselect greatest(1.2,2.3) from dualselect least(1.2,2.3) from dual9) To Round a number.A. select ceil(1208917.97802706) from dual;10) To Truncate a number.A. select floor(1208917.97802706) from dual;11) Select employees who joined before their manager.A. select a.empno,a.ename from emp a, emp b where a.mgr=b.empno and a.hiredate< b.hiredate;11) To Select Only Characters from a combination of numbers and characters.select translate

('RAGHU40020','ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ') FROM dual;

12) To get those employee whose name ends with 'RD' :select * from emp where ename like '%RD';13) To select those , whose last names are a phonetic representation of 'SMYTHE' :select * from emp where soundex(ename)=soundex('SMYTHE')To select those , whose job is phonetic representation of 'SALESMEN' :select * from emp where soundex(job)=soundex('SALESMEN');14) To display employee details of workers who joined before their managers :select a.ename from emp a, emp b where a.mgr=b.empno and a.hiredate<b.hiredate;15) Display the names of employees whose sal is greater than max sal of sales :select * from emp where sal >(select max(sal) from emp , dept where emp.deptno=dept.deptno and dname='SALES');16) Display the employee name , who is drawing histet salary :select * from emp where sal=(select max(sal) from emp);17) TO list the employees in deptno =10 with common jobs in depnto=20 :select a.ename,a.empno,b.ename,b.empno from emp a , emp b wherea.job=b.job and a.deptno=10 and b.deptno=20;18) To list the employees who have both the same job and same salary as SCOTT :

Page 2: Complete SQL Commands

select * from emp where job=(select job from emp where ename='SCOTT')and sal=(select sal from emp where ename='SCOTT') and ename!='SCOTT'19) List the employees who have the same job as SMITH or Sal < Jones in order by job,sal :select * from emp where job=(select job from emp where ename='SMITH') or sal <(select sal from emp where ename='JONES')order by job,sal20) Select all employees where ENAME should not begin with A :select * from emp where ename not like 'A%';21) Display last three characters of each employee :select ename, substr(ename,-3) from emp;From last three characters of name , display first two characters :select ename, substr(ename,-3,2) from emp;22) To Display the names of employees whose name have two A's in their name :select * from emp where ename like 'A%A' or ename like '%AA%' or ename like '%A%A%';23) List the details of employees whose sal is greater than average sal :select * from emp where sal >(select avg(sal) from emp);24) Select Minium, Maxium, Average Salaries Department wise :select min(sal),max(sal),avg(sal),deptno from emp group by deptno;25) Display the number of employees in each department :select count(*),deptno from emp group by deptno;26) List the average sal for all employees :select avg(sal) from emp;27) Display all employees whose department is 10 :select * from emp where deptno=10;28) Display all employees whose sal lie between 2000 and 5000 :select * from emp where deptno=10;29) Display names of all employees whose name starts with letter 'S' :select * from emp where ename like 'S%';30) List names of all employees whose name have more than FIVE letters :select ename from emp where ename like'%5';31) Display the names of employees whose name have only four letters :select * from emp where ename like '____';32) To select Day from a date :For day :select to_char(hiredate,'dd') from emp;For Week :select to_char(hiredate,'day') from emp;33) To select Month from a date :For Month in Number :select to_char(hiredate,'mm') from empFor Month in Characters :select to_char(hiredate,'mon') from emp34) To select Year from a date :select to_char(hiredate,'yy') from empselect to_char(hiredate,'yyyy') from emp35) Display details of employees who joined in February;

select * from emp where to_char(hiredate,'mm')=2;select * from emp where hiredate like '%FEB%';36) List the details of employees who joined after 1st December 1980 and before 1st December 1981 :select * from emp where hiredate between to_date('01-12-1980','dd-mm-yyyy') and to_date('01-12-1981','dd-mm-yyyy')37) List the details of employees who earn more than 2000 and doesnot enjoy any comm :select * from emp where sal > 2000 and comm is null;38) List the details of employees who joined before 20th of any month and year except 1981 :select * from emp where to_char(hiredate,'dd') < 20 and to_char(hiredate,'yyyy') != 198139) List the deatils of employees who enjoy comm more than 250 :select * from emp where comm >250;40) List the sum of Sal and Comm (Assume , if comm is null , then comm = 0 ) :select sal,comm,sal+nvl(comm,0) from emp;

Page 3: Complete SQL Commands

(Assume , if comm is null , then comm = 100 ) :select sal,comm,sal+nvl(comm,100) from emp;41) List the department name and location for emplyoees who earn more than 1500 :select a.ename,b.deptno,dname,loc,sal from emp a,dept b wherea.deptno=b.deptno and a.sal >150042) Select Last three characters of each employee :select ename,substr(ename,-3,3) from emp;43) Display the employee id , employee name and their salaries Prefix with Dollar sign indecending order :column sal format $99,990select sal from emp;44) Display Job ( Replacing 'SALESMAN' with 'SALESPERSON' ) of employees :select job,decode(job,'SALESMAN','SALESPERSON',job) FROM emp45) Display deptname , in which no employee has been recruited :select deptno,dname,loc from dept where deptno=(select deptno from dept minus select distinct deptno from emp);46) In which year maximum employee were recruited :select to_char(hiredate,'yy') from emp having count(*)=(select max(count(*)) from emp group by to_char(hiredate,'yy')) group by to_char(hiredate,'yy')47) Display departments which has more than 3 employees :select deptno from emp having count(*) >3 group by deptno;48) List out number of clerks and number of managers :select count(*), job from emp where job='CLERK' or job='MANAGER' group by job;49) List most experienced employee :select * from emp where hiredate=(select min(hiredate) from emp);50) List employees who celebrate their birthday in current month :select * from emp where to_char(hiredate,'mm')=to_char(sysdate,'mm');51) Display the details of employees completing 20 years of service :select * from emp where months_between(sysdate,hiredate) > 240;Here , 240 months means 20 years52) Display the details of employees who have joined before BLAKE :select * from emp where hiredate < ( select hiredate from emp where ename='BLAKE');53) Display sal of employees with information :Greater , if sal > 1500Lesser , if sal < 1500Equal , if sal = 1500select sal, decode(sign(sal-1500),1,'Greater',-1,'Lesser','Equal') from emp;54) Display number of employees joined in year 81 :select count(*) from emp where to_char(hiredate,'yy') = 81;55) Display all employees who joined before 28-sep-81 :select * from emp where to_date(hiredate,'dd-mon-yy') < to_date('28-sep-81','dd-mon-yy');56) Display all employees who joined after 09-jun-81 :select * from emp where to_date(hiredate,'dd-mon-yy') > to_date('09-jun-81','dd-mon-yy');57) To get a equalent Character for a ASCII value :select chr(67) from dual;58) To get a ASCII value for a character :select ascii('C') from dual;59) Display the list who joined between 20-feb-81 and 03-dec-81 :select * from emp where to_date(hiredate,'dd-mon-yy') between to_date('20-feb-81','dd-mon-yy') and to_date('03-dec-81','dd-mon-yy');60) Select number of managers :select count(*) from emp where job='MANAGER';61) List the number of employees in each dept :select count(*),deptno from emp group by deptno;62) List the employees , who are earning same salary :select a.ename,b.ename from emp a , emp b where a.deptno=b.deptno and a.sal=b.sal and a.empno!=b.empno;63) Display the first five rows :select * from emp where rownum<6;64) Display details about 5th employee :

Page 4: Complete SQL Commands

select * from emp where rownum < 6 minus select * from emp where rownum < 5;65) List out the details of those employees whose salary is greter than the average salary of their dept :select ename,sal from emp where ename=(select avg(sal)from emp);66) List the last five employees from emp :select * from emp minus select * from emp where rownum < 10;67) Write a query to increment basic salary (salary + comm) by 10% for those employees whosebasic salary is less than 1000 and 20% :select sal,decode(sal,sal,(sal+0.1*sal+nvl(comm,0))) from emp where sal <=1000unionselect sal,decode(sal,sal,(sal+0.2*sal+nvl(comm,0))) from emp where sal >=100068) Display the top 3 salaries from emp table :select sal from emp where sal>50000;69) Display experience of each employee :select months_between(sysdate,hiredate) from emp;

70) Display most expereiced employee :select ename fro emp where hiredate=(select greater hiredate from emp);71) Display the list of employees , number of employees joined in each year :select count(*), to_char(hiredate,'yyyy') from emp group by to_char(hiredate,'yyyy');72) Dislpaly the year in which , maximum employees recruited :select to_char(hiredate,'yy') from emp having count(*)=(select max(count(*)) from emp group by to_char(hiredate,'yy') ) group by to_char(hiredate,'yy');73) TRUNC :select trunc(15.7) from dual; output --> 15select trunc(15.4) from dual; output --> 15select trunc(15.678,2) from dual; output --> 15.67select trunc(15.678,1) from dual; output --> 15.6select trunc(15.678,-1) from dual; output --> 10select trunc(15.678,-2) from dual; output --> 0select trunc(115.678,-2) from dual; output --> 100select trunc(115.678,-3) from dual; output --> 074) ROUND :select round(15.7) from dual; output --> 16select round(15.4) from dual; output --> 15select round(115.5,-1) from dual; output --> 120select round(115.5,-2) from dual; output --> 10075) MOD :select mod(99,4) from dual; output --> 376) Operators :select 5/2 from dual; output --> 2.5select 5*3 from dual; output --> 15select 5+3 from dual; output --> 8select 5-3 from dual; output --> 277) FLOOR :select floor(3.4) from dual; output --> 3select floor(3.7) from dual; output --> 378) CEIL :select ceil(3.4) from dual; output -->4select ceil(3.7) from dual; output -->479) SUBSTR :select ename,substr(ename,1,3) from emp;select ename,substr(ename,-3,3) from emp;80 ) TRANSLATE :select translate('RAGHU40020','ABCDEFGHIJKLMNOPQRSTUVWXYZ012345789','ABCDEFGHIJKLMNOPQRSTUVWXYZ') from dual;select translate('RAGHU40020','ABCDEFGHIJKLMNOPQRSTUVWXYZ012345789',' 0123456789') from dual81) INSTR :It used to search the place of a substring in a string.select instr('RAGHU','G',1) from dual; output --> 3

Page 5: Complete SQL Commands

select instr('RAGHU','GH',1) from dual; output --> 3select instr('RAGHU','GU',1) from dual; output --> 082) Arthmatic Fuction :sin,sinh,cos,cosh,tan,tanh etc..select sin(A) from dual; NOTE : A should be in Radiansselect sin(30) from dual; output --> -.98803162select exp(2) from dual; output --> 7.3890561select log(100,10) from dual; output --> 0.5LOG takes two arguments.select ln(10) from dual; output --> 2.30258509POWER :To raise one number to the power of another , use power. In this function the first argument is raised to the power of second argument.select power(2,3) from dual; output --> 8select power(-2,3) from dual; output --> -8select power(2,-3) from dual; output --> 0.125select power(-2,-3) from dual; output --> -0.12583) SIGN :Sign returns 1 if its argument is greater than zero, -1 if its argument is lesser than zero , 0 if its argument is equal to zero.select sign(10-2) from dual; output --> 1select sign(2-10) from dual; output --> -1select sign(3-3) from dual; output --> 084) SQRT :select sqrt(16) from dual; output --> 485) LPAD,RPAD :select lpad('Raghu',4) from dual; output --> Raghselect lpad('Raghu',2) from dual; output --> Raselect lpad('Raghu',1) from dual; output --> Rselect rpad('Raghu',2) from dual; output --> Raselect rpad('Raghu',4) from dual; output --> Ragh

Concepts and Architecture of Database Structures Part- I   

Page 6: Complete SQL Commands

1. What are the components of Physical database structure of Oracle Database?             ORACLE database is comprised of three types of files. One or more Data files, two are more Redo Log files, and one or more Control files. 2. What are the components of Logical database structure of ORACLE database?             Tablespaces and the Database's Schema Objects 3. What is a Tablespace?             A database is divided into Logical Storage Unit called tablespaces. A tablespace is used to grouped related logical structures together. 4. What is SYSTEM tablespace and when is it Created?             Every ORACLE database contains a tablespace named SYSTEM, which is automatically created when the database is created. The SYSTEM tablespace always contains the data dictionary tables for the entire database. 5. Explain the relationship among Database, Tablespace and Data file.             Each databases logically divided into one or more tablespaces one or more data files are explicitly created for each tablespace. 6. What is schema?            A schema is collection of database objects of a User. 7. What are Schema Objects?             Schema objects are the logical structures that directly refer to the database's data.  Schema objects include tables, views, sequences, synonyms, indexes, clusters, database triggers, procedures, functions packages and database links. 8. Can objects of the same Schema reside in different tablespaces?             Yes. 9. Can a Tablespace hold objects from different Schemes?             Yes. 10. What is Table?             A table is the basic unit of data storage in an ORACLE database. The tables of a database hold all of the user accessible data. Table data is stored in rows and columns. 

11. What is a View?             A view is a virtual table. Every view has a Query attached to it. (The Query is a SELECT statement that identifies the columns and rows of the table(s) the view uses.) 12. Does View contain Data?             Views do not contain or store data. 13. Can a View based on another View?             Yes. 14. What are the advantages of Views?             Provide an additional level of table security, by restricting access to a predetermined set of rows and columns of a table. Hide data complexity. Simplify commands for the user present the data in a different perspective from that of the base table. Store complex queries. 15. What is a Sequence?             A sequence generates a serial list of unique numbers for numerical columns of a database's tables.  

Page 7: Complete SQL Commands

16. What is a Synonym?             A synonym is an alias for a table, view, sequence or program unit. 17. What are the types of Synonyms?             There are two types of Synonyms Private and Public. 18. What is a Private Synonyms?             A Private Synonyms can be accessed only by the owner. 19. What is a Public Synonym?             Public synonyms can be accessed by any user on the database. 20. What are synonyms used for?             Synonyms are used to: 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 database. Simplify the SQL statements for database users. 

  21. What is an Index?            An Index is an optional structure associated with a table to have direct access to rows, which can be created to increase the performance of data retrieval.  Index can be created on one or more columns of a table. 22. How is Indexes Update?             Indexes are automatically maintained and used by ORACLE. Changes to table   data are automatically incorporated into all relevant indexes. 23. What are Clusters?             Clusters are groups of one or more tables physically stores together to share common columns and are often used together. 24. What is cluster Key?             The related columns of the tables in a cluster are called the Cluster Key.  25. What is Index Cluster?             A Cluster with an index on the Cluster Key 26. What is Hash Cluster?             A row is stored in a hash cluster based on the result of applying a hash function to the row's cluster key value. All rows with the same hash key value are stores together on disk. 27. When can Hash Cluster used?             Hash clusters are better choice when a table is often queried with equality queries. For such queries the specified cluster key value is hashed. The resulting hash key value points directly to the area on disk that stores the specified rows. 28. What is Database Link?             A database link is a named object that describes a "path" from one database to another. 29. What are the types of Database Links?             Private Database Link, Public Database Link & Network Database Link. 30. What is Private Database Link?             Private database link is created on behalf of a specific user. A private database link can be used only when the owner of the link specifies a global object name in a SQL statement or in the definition of the owner's views or procedures. 

Page 8: Complete SQL Commands

  31. What is a Data File?             Every ORACLE database has one or more physical data files. A database's data files contain all the database data. The data of logical database structures such as tables and indexes is physically stored in the data files allocated for a database. 32. What are the Characteristics of Data Files?             A data file can be associated with only one database. Once created a data file can't change size. One or more data files form a logical unit of database storage called a tablespace. 33. What is a Redo Log?             The set of Redo Log files for a database is collectively known as the database's redo log.  34. What is the function of Redo Log?             The Primary function of the redo log is to record all changes made to data.  35. What is the use of Redo Log Information?             The Information in a redo log file is used only to recover the database from a system or media failure prevents database data from being written to a database's data files.  36. What does a Control file Contain?             A  Control file records the physical structure of the database. It contains the following information. Database Name Names and locations of a database's files and redo log files.  Time stamp of database creation  37. What is the use of Control File?             When an instance of an ORACLE database is started, its control file is used to identify the database and redo log files that must be opened for database operation to proceed. It is also used in database recovery. 38. What is a Data Dictionary?             The data dictionary of an ORACLE database is a set of tables and views that are used as a read-only reference about the database. It stores information about both the logical and physical structure of the database, the valid users of an ORACLE database, integrity constraints defined for tables in the database and space allocated for a schema object and how much of it is being used.  39. What is an Integrity Constrains?             An integrity constraint is a declarative way to define a business rule for a column of a table. 40. Can an Integrity Constraint be enforced on a table if some existing table data does not satisfy the constraint?             No. 

 41. Describe the different type of Integrity Constraints supported by ORACLE?•        NOT NULL Constraint - Disallows Nulls in a table's column.•        UNIQUE Constraint - Disallows duplicate values in a column or set of columns.•        PRIMARY KEY Constraint - Disallows duplicate values and Nulls in a column or set of            columns.•        FOREIGN KEY Constrain - Require each value in a column or set of columns match a value    in a related table's UNIQUE or PRIMARY KEY.•        CHECK Constraint - Disallows values that do not satisfy the logical expression of the    constraint.  42. What is difference between UNIQUE constraint and PRIMARY KEY constraint?

Page 9: Complete SQL Commands

             A column defined as UNIQUE can contain Nulls while a column defined as PRIMARY KEY can't contain Nulls.  43. Describe Referential Integrity?             A rule defined on a column (or set of columns) in one table that allows the insert or update of  a  row only if the value for the column or set of columns (the  dependent  value) matches a value in a column of a related table (the referenced value). It also specifies the type of data manipulation allowed on referenced data and the action to be performed on dependent data as a result of any action on referenced data. 44. What is Public Database Link?             Public database link is created for the special user group PUBLIC. A public database  link  can  be  used  when  any  user  in  the associated database specifies a global object name in a SQL  statement or object definition. 45. What is Network Database link?             Network database link is created and managed by a network domain service. A network database link can be used when any user of any database in the network specifies a global object name in a SQL statement or object definition. 46. What is Data Block?             ORACLE database's data is stored in data blocks. One data block corresponds to a specific number of bytes of physical database space on disk. 47. What is Row Chaining?            In Circumstances, all of the data for a row in a table may not be able to fit in the same data block. When this occurs, the data for the row is stored in a chain of data block (one or more) reserved for that segment.  48. What is an Extent?             An   Extent is a specific number of contiguous data blocks, obtained in a single allocation, and used to store a specific type of information.  49. What is a Segment?            A segment is a set of extents allocated for a certain logical structure. 50. What is the different type of Segments?            Data Segment, Index Segment, Rollback Segment and Temporary Segment 

  51. What is a Data Segment?            Each Non-clustered table has a data segment. All of the table's data is stored in the extents of its data segment. Each cluster has a data segment. The data of every table in the cluster is stored in the cluster's data segment.  52. What is an Index Segment?            Each Index has an Index segment that stores all of its data.  53. What is Rollback Segment?            A  Database contains one or more Rollback Segments to temporarily store "undo" information.  54. What are the uses of Rollback Segment?

Page 10: Complete SQL Commands

             Rollback Segments are used:   To generate read-consistent database information during database recovery to rollback uncommitted transactions for users.  55. What is a Temporary Segment?             Temporary  segments  are  created  by  ORACLE  when a SQL statement needs a temporary  work  area  to  complete  execution. When the statement finishes execution, the temporary segment extents are released to the system for future use. 56. What are the Referential actions supported by FOREIGN KEY integrity constraint?             UPDATE and DELETE Restrict - A referential integrity rule that disallows the update or deletion of referenced data.             DELETE Cascade - When a referenced row is deleted all associated dependent rows are deleted.  57. What is self-referential integrity constraint?             If a foreign key reference a parent key of the same table is called self-referential integrity constraint. 58. What are the Limitations of a CHECK Constraint?             The condition must be a Boolean expression evaluated using the values in the row being inserted or updated and can't contain sub queries, sequence, the SYSDATE,UID,USER  or  USERENV SQL functions, or the pseudo columns LEVEL or ROWNUM. 59. What is the maximum number of CHECK constraints that can be defined on a column? No Limit.  

 SYSTEM ARCHITECTURE: 1. What constitute an ORACLE Instance?             SGA and ORACLE background processes constitute an ORACLE instance. (Or) Combination of memory structure and background process 2. What is SGA?                            The System Global Area (SGA) is a shared memory region allocated by ORACLE that contains data and control information for one ORACLE instance. 3. What are the components of SGA?                              Database buffers, Redo Log Buffer the Shared Pool and   Cursors. 4. What do Database Buffers contain?                            Database buffers store the most recently used blocks of database data. It can also contain modified data that has not yet been permanently written to disk. 5. What do Redo Log Buffers contain?                         Redo Log Buffer stores redo entries a log of changes made to the database. 6. What is Shared Pool?                      Shared Pool is a portion of the SGA that contains shared memory constructs such as shared SQL areas. 7. What is Shared SQL Area?                      A  Shared SQL area is required to process every unique SQL statement submitted to a database and contains information such as the parse tree and execution plan for the corresponding statement. 8. What is Cursor?                      A  Cursor is a handle (a name or pointer) for the memory associated with a specific statement.

Page 11: Complete SQL Commands

 9. What is PGA?                      Program Global Area (PGA) is a memory buffer that contains data and control information for a server process. 10. What is User Process?                      A user process is created and maintained to execute the software code of an application program. It is a shadow process created automatically to facilitate communication between the user and the server process.

Concepts and Architecture of Database Structures Part- 2   1. What is Server Process?            Server Process handles requests from connected user process. A server process is in charge of communicating with the user process and interacting with ORACLE carry out requests of the associated user process. 2. What are the two types of Server Configurations?            Dedicated Server Configuration and Multi-threaded Server Configuration 3. What is Dedicated Server Configuration?            In a Dedicated Server Configuration a Server Process handles requests for a Single User Process. 4. What is a Multi-threaded Server Configuration?                    In a Multi-threaded Server Configuration many user processes share a group of server process. 5. What is a Parallel Server option in ORACLE?            A configuration for loosely coupled systems where multiple instances share a single physical database is called Parallel Server. 6. Name the ORACLE Background Process?            

DBWR - Database WriterLGWR - Log WriterCKPT - Check PointSMON - System MonitorPMON - Process MonitorARCH - ArchiverRECO - RecoverDnnn - Dispatcher, andLCKn - LockSnnn - Server.

 7. What Does DBWR do?             Database writer writes modified blocks from the database buffer cache to the data files. 8. When Does DBWR write to the database?             DBWR writes when more data needs to be read into the SGA and too few database buffers are free. The least recently used data is written to the data files first. DBWR also writes when Checkpoint occurs. 9. What does LGWR do?            Log Writer (LGWR) writes redo log entries generated in the redo log buffer of the SGA to on-line Redo Log File. 

Page 12: Complete SQL Commands

10. When does LGWR write to the database?             LGWR   writes  redo  log  entries  into  an  on-line  redo  log  file  when transactions commit and the log buffer files are full. 

11. What is the function of checkpoint (CKPT)?            The  Checkpoint  (CKPT)  process  is  responsible  for  signalling  DBWR  at checkpoints  and  updating  all  the  data  files  and control files of the database.  12. What are the functions of SMON?            System Monitor (SMON) performs instance recovery at instance start-up. In a multiple instance system (one that uses the Parallel Server), SMON of one instance  can  also  perform instance recovery for other instance that have failed SMON also cleans up temporary segments that are no longer in use and recovers  dead  transactions  skipped  during  crash  and instance recovery because of  file-read or off-line errors. These transactions are eventually recovered  by SMON when the tablespace or file is brought back on-line SMON also coalesces  free  extents  within  the  database  to  make  free space contiguous and easier to allocate. 13. What are functions of PMON?            Process Monitor (PMON)  performs process recovery when a user process fails PMON  is  responsible  for cleaning up the cache and Freeing resources that the  process  was using PMON also checks on dispatcher and server processes and restarts them if they have failed. 14. What is the function of ARCH?            Archiver (ARCH) copies the on-line redo log files to archival storage when they are full.  ARCH is active only when a database's redo log is used in ARCHIVELOG mode. 15. What is function of RECO?            Recover (RECO) is used to resolve distributed transactions that are pending due to a network or system failure in a distributed database. At timed intervals, the local RECO attempts to connect to remote databases and automatically complete the commit or rollback of the local portion of any pending distributed transactions. 16. What is the function of Dispatcher (Dnnn)?             Dispatcher (Dnnn) process is responsible for routing requests from connected user processes to available shared server processes and returning the responses back to the appropriate user processes. 17. How many Dispatcher Processes are created?            At least one Dispatcher process is created for every communication protocol in use. 18. What is the function of Lock (LCKn) Process?             Lock (LCKn) is used for inter-instance locking when the ORACLE Parallel Server option is used. 19. What is the maximum number of Lock Processes used?            Though a single LCK process is sufficient for most Parallel Server systemsUp to Ten Locks (LCK0, LCK9) are used for inter-instance locking.   

DATA ACCESS             Archiver (ARCH) copies the on-line redo log files to archival storage when they are full.  ARCH is active only when a database's redo log is used in ARCHIVELOG mode. 1. What is function of RECO? 

Page 13: Complete SQL Commands

            Recover (RECO) is used to resolve distributed transactions that are pending due to a network or system failure in a distributed database. At timed intervals, the local RECO attempts to connect to remote databases and automatically complete the commit or rollback of the local portion of any pending distributed transactions. 2. What is the function of Dispatcher (Dnnn)?            Dispatcher   (Dnnn) process is responsible for routing requests from connected user processes to available shared server processes and returning the responses back to the appropriate user processes. 3. How many Dispatcher Processes are created?             At least one Dispatcher process is created for every communication protocol in use. 4. What is the function of Lock (LCKn) Process?            Lock (LCKn) is used for inter-instance locking when the ORACLE Parallel Server option is used. 5. What is the maximum number of Lock Processes used?           Though a single LCK process is sufficient for most Parallel Server systems. Up to Ten Locks (LCK0, LCK9) are used for inter-instance locking.  

DATA MANIPULATION 1. When does a Transaction end?            When it is committed or Roll backed. 2. What does COMMIT do?           COMMIT makes permanent the changes resulting from all SQL statements in the transaction. The changes made by the SQL statements of a transaction become visible   to other user sessions transactions that start only after transaction is committed. 3. What does ROLLBACK do?            ROLLBACK retracts any of the changes resulting from the SQL statements in the transaction. 4. What is SAVE POINT?            For  long  transactions  that  contain  many  SQL  statements, intermediate markers  or  save points  can  be  declared  which  can be used to divide a transaction  into  smaller  parts.  This allows the option of later rolling back all work performed from the current point in the transaction to a declared save point within the transaction. 5. What is Read-Only Transaction?            A  Read-Only transaction ensures that the results of each query executed in the transaction are consistent with respect to the same point in time. 6. What is the function of Optimizer?            The goal of the optimizer is to choose the most efficient way to execute a SQL statement.  7. What is Execution Plan?            The combination of the steps the optimizer chooses to execute a statement is called an execution plan. 8. What are the different approaches used by Optimizer in choosing an execution plan?            Rule-based and Cost-based 9. What are the factors that affect OPTIMIZER in choosing an Optimization approach?            The   OPTIMIZER_MODE   initialization parameter Statistics in the Data Dictionary the OPTIMIZER_GOAL parameter of the ALTER SESSION command hints in the statement. 10. What are the values that can be specified for OPTIMIZER MODE Parameter?

Page 14: Complete SQL Commands

            COST and RULE 

 11. Will the Optimizer always use COST-based approach if OPTIMIZER_MODE is set to "Cost'?            Presence of statistics in the data dictionary for at least one of the tables accessed by the SQL statements is necessary for the OPTIMIZER to use COST-based approach. Otherwise OPTIMIZER chooses RULE-based approach. 12. What is the effect of setting the value of OPTIMIZER_MODE to ‘RULE’?            This value causes the optimizer to choose the rule based approach for all SQL statements issued to the instance regardless of the presence of statistics. 13. What are the values that can be specified for OPTIMIZER_GOAL parameter of the ALTER SESSION Command?           CHOOSE, ALL_ROWS, FIRST_ROWS and RULE. 14. What is the effect of setting the value "CHOOSE" for OPTIMIZER_GOAL, parameter of the ALTER SESSION Command?            The Optimizer chooses Cost based approach and optimizes with the goal of best throughput if statistics for at least one of the tables accessed by the SQL statement exist in the data dictionary. Otherwise the OPTIMIZER chooses RULE based approach. 15. What is the effect of setting the value "ALL_ROWS” for OPTIMIZER_GOAL parameter of the ALTER SESSION command?            This value causes the optimizer to the cost-based approach for all SQL statements in the session regardless of the presence of statistics and to optimize with a goal of best throughput.  16. What is the effect of setting the value ‘FIRST_ROWS’ for OPTIMIZER_GOAL parameter of the ALTER SESSION command?            This value causes the optimizer to use the cost-based approach for all SQL statements in the session regardless of the presence of statistics and to optimize with a goal of best response time. 17. What is the effect of setting the 'RULE' for OPTIMIER_GOAL parameter of the ALTER SESSION Command?            This value causes the optimizer to choose the rule-based approach for all SQL statements in a session regardless of the presence of statistics. 18. What is RULE-based approach to optimization?            Choosing an executing plan based on the access paths available and the ranks of these access paths. 19. What is COST-based approach to optimization?             Considering  available  access  paths  and  determining  the most efficient execution  plan  based  on statistics in the data dictionary for the tables accessed by the statement and their associated  clusters and indexes. 

 PROGRAMMATIC CONSTRUCTS  1. What are the different types of PL/SQL program units that can be defined and stored in ORACLE database?            Procedures and Functions, Packages and Database Triggers 2. What is a Procedure?

Page 15: Complete SQL Commands

           A  Procedure consist of a set of SQL and PL/SQL statements that are grouped together  as a unit to solve a specific problem or perform a set of related tasks. 3. What is difference between Procedures and Functions?            A Function returns a value to the caller where as a Procedure does not. 4. What is a Package?             A  Package is a collection of related procedures, functions, variables and other package constructs together as a unit in the database. 5. What are the advantages of having a Package?             Increased  functionality  (for  example,global  package  variables  can  be declared  and  used  by  any proecdure in the package) and performance (for example  all  objects  of  the package are parsed compiled, and loaded into memory once) 6. What is Database Trigger?            A Database Trigger is procedure (set of SQL and PL/SQL statements) that is automatically executed as a result of an insert in,update to, or delete from a table. 7. What are the uses of Database Trigger?            Database triggers can be used to automatic data generation, audit data modifications, enforce complex Integrity constraints, and customize complex security authorizations. 8. What are the differences between Database Trigger and Integrity constraints?            A declarative integrity constraint is a statement about the database that is always true. A constraint applies to existing data in the table and any statement that manipulates the table.             A trigger does not apply to data loaded before the definition of the trigger; therefore, it does not guarantee all data in a table conforms to the rules established by an associated trigger.             A trigger can be used to enforce transitional constraints where as a declarative integrity constraint cannot be used.  

DATABASE SECURITY 1. What are Roles?             Roles are named groups of related privileges that are granted to users or other roles. 2. What is the use of Roles?             REDUCED  GRANTING  OF PRIVILEGES - Rather than explicitly granting the same set  of  privileges  to  many users a database administrator  can grant the privileges  for  a  group of related users granted to a role and then grant only the role to each member of the group.             DYNAMIC PRIVILEGE MANAGEMENT - When the privileges of a group must change, only the privileges of the role need to be modified. The security domains of all users granted the group's role automatically reflect the changes made to the role.             SELECTIVE AVAILABILITY OF PRIVILEGES - The roles granted to a user can be selectively enable (available for use) or disabled (not available for use).  This allows specific control of a user's privileges in any given situation.             APPLICATION AWARENESS - A database application can be designed to automatically enable and disable selective roles when a user attempts to use the application.

Page 16: Complete SQL Commands

Concepts and Architecture of Database Structures Part - 3   1. How to prevent unauthorized use of privileges granted to a Role?             By creating a Role with a password. 2. What is default tablespace?            The Tablespace to contain schema objects created without specifying a tablespace name. 3. What is Tablespace Quota?            The collective amount of disk space available to the objects in a schema on a particular tablespace. 4. What is a profile?            Each database user is assigned a Profile that specifies limitations on various system resources available to the user. 5. What are the system resources that can be controlled through Profile?            The number of concurrent sessions the user can establish the CPU processing time available to the user's session the CPU processing time available to a single call to ORACLE  made by a SQL statement the amount of logical I/O available to the user's session the amount of logical I/O available to a single call to ORACLE made by a SQL statement the allowed amount of idle time for the user's session the allowed amount of connect time for the user's session. 6. What is Auditing?            Monitoring of user access to aid in the investigation of database use. 7. What are the different Levels of Auditing?            Statement Auditing, Privilege Auditing and Object Auditing. 8. What is Statement Auditing?            Statement auditing is the auditing of the powerful system privileges without regard to specifically named objects. 9. What is Privilege Auditing?            Privilege auditing is the auditing of the use of powerful system privileges without regard to specifically named objects. 10. What is Object Auditing?            Object auditing is the auditing of accesses to specific schema objects without regard to user. 

 

 DISTRIBUTED PROCESSING AND DISTRIBUTED DATABASES  1. What is Distributed database?            A  distributed  database  is  a  network  of  databases managed by multiple database  servers  that  appears  to a user as single logical database. The data of all databases in the distributed database can be simultaneously accessed and modified. 2. What is Two-Phase Commit?            Two-phase commit is mechanism that guarantees a distributed transaction either commits on all involved nodes or rolls back on all involved nodes to maintain data consistency across the global distributed database. It has two phases, a Prepare Phase and a Commit Phase. 3. Describe two phases of Two-phase commit?

Page 17: Complete SQL Commands

            Prepare phase - The global coordinator (initiating node) ask a participants to prepare   (to promise to commit or rollback the transaction, even if there is a failure)             Commit - Phase - If all participants respond to the coordinator that they are prepared, the coordinator asks all nodes to commit the transaction, if all participants cannot prepare, and the coordinator asks all nodes to roll back the transaction. 4. What is the mechanism provided by ORACLE for table replication?            Snapshots and SNAPSHOT LOGs 5. What is a SNAPSHOT?            Snapshots are read-only copies of a master table located on a remote node which is periodically refreshed to reflect changes made to the master table.  6. What is a SNAPSHOT LOG?            A snapshot log is a table in the master database that is associated with the master table.  ORACLE uses a snapshot log to track the rows that have been updated in the master table. Snapshot logs are used in updating the snapshots based on the master table. 7. What is a SQL * NET?            SQL *NET is Oracle’s mechanism for interfacing with the communication protocols used by the networks that facilitate distributed processing and distributed databases.  It is used in Clint-Server and Server-Server communications. 

 DATABASE OPERATION, BACKUP AND RECOVERY 1. What are the steps involved in Database Startup?            Start an instance, Mount the Database and Open the Database. 2. What are the steps involved in Database Shutdown?            Close the Database; Dismount the Database and Shutdown the Instance. 3. What is Restricted Mode of Instance Startup?            An instance can be started in (or later altered to be in) restricted mode so that when the database is open connections are limited only to those whose user accounts have been granted the RESTRICTED SESSION system privilege. 4. What are the different modes of mounting a Database with the Parallel Server?            Exclusive Mode If the first instance that mounts a database does so in exclusive mode, only that Instance can mount the database.             Parallel Mode If the first instance that mounts a database is started in parallel mode, other instances that are started in parallel mode can also mount the database. 5. What is full backup?            A full backup is an operating system backup of all data files, on-line redo log files and control file that constitute ORACLE database and the parameter. 6. Can Full Backup be performed when the database is open?             No. 7. What is Partial Backup?             A Partial Backup is any operating system backup short of a full backup, taken while the database is open or shut down.

Page 18: Complete SQL Commands

 8. What is On-line RedoLog?             The On-line Redo Log is a set of tow or more on-line redo files that record all committed changes made to the database. Whenever a transaction is committed,  the  corresponding  redo entries temporarily stores in redo log buffers  of  the  SGA  are  written  to  an  on-line redo  log file by the background  process  LGWR.  The on-line redo log files are used in cyclical fashion. 9. What is Mirrored on-line Redo Log?            A mirrored on-line redo log consists of copies of on-line redo log files physically located on separate disks; changes made to one member of the group are made to all members. 10. What is Archived Redo Log?            Archived Redo Log consists of Redo Log files that have archived before being reused. 11. What are the advantages of operating a database in ARCHIVELOG mode over operating it in NO ARCHIVELOG mode?            Complete database recovery from disk failure is possible only in ARCHIVELOG mode.Online database backup is possible only in ARCHIVELOG mode. 12. What is Log Switch?            The point at which ORACLE ends writing to one online redo log file and begins writing to another is called a log switch.  13. What are the steps involved in Instance Recovery?            Rolling forward to recover data that has not been recorded in data files yet has been recorded in the on-line redo log, including the contents of rollback segments.             Rolling back transactions that have been explicitly rolled back or have not been committed as indicated by the rollback segments regenerated in step a.Releasing any resources (locks) held by transactions in process at the time of the failure.             Resolving any pending distributed transactions undergoing a two-phase commit at the time of the instance failure.  

DATABASE ADMINISTRATION Introduction to DBA 1. What is a Database instance? Explain             A database instance (Server) is a set of memory structure and background processes that access a set of database files.             The process can be shared by all users.             he  memory  structure  that  are  used  to  store  most  queried data from database.  This helps up to improve database performance by decreasing the amount of I/O performed against data file. 2. What is Parallel Server?            Multiple instances accessing the same database (Only in Multi-CPU environments) 3. What is a Schema?             The set of objects owned by user account is called the schema. 4. What is an Index? How it is implemented in Oracle Database?

Page 19: Complete SQL Commands

            An index is a database structure used by the server to have direct access of a row in a table. An index is automatically created when a unique of primary key constraint clause is specified in create table comman (Ver 7.0) 5. What are clusters?            Group of tables physically stored together because they share common columns and are often used together is called Cluster. 6. What is a cluster Key?          The related columns of the tables are called the cluster key.  The cluster key is indexed using a cluster index and its value is stored only once for multiple tables in the cluster. 7. What is the basic element of Base configuration of an oracle Database?It consists of            One or more data files.            One or more control files.            Two or more redo log files.The Database contains            Multiple users/schemas            One or more rollback segments            One or more tablespaces            Data dictionary tables            User objects (table,indexes,views etc.,)The server that access the database consists of            SGA (Database buffer, Dictionary Cache Buffers, Redo log buffers, Shared SQL pool)            SMON (System MONito)            PMON (Process MONitor)            LGWR (LoG Write)            DBWR (Data Base Write)            ARCH (ARCHiver)            CKPT (Check Point)            RECO            Dispatcher            User Process with associated PGS  8. What is a deadlock? Explain.            Two processes wating to update the rows of a table which are locked by the other process then deadlock arises.             In a database environment this will often happen because of not issuing proper row lock commands. Poor design of front-end application may cause this situation and the performance of server will reduce drastically.             These locks will be released automatically when a commit/rollback operation performed or any one of these processes being killed externally.   

MEMORY MANAGEMENT 1. What is SGA? How it is different from Ver 6.0 and Ver 7.0?            The System Global Area in a Oracle database is the area in memory to facilitates the transfer of information between users. It holds the most recently requested structural information between users. It holds the most recently requested structural information about the database. The structure is Database buffers, Dictionary cache, and Redo Log Buffer and Shared SQL pool (ver. 7.0 only) area. 

Page 20: Complete SQL Commands

2. What is a Shared SQL pool?            The data dictionary cache is stored in an area in SGA called the Shared SQL Pool.  This will allow sharing of parsed SQL statements among concurrent users. 3. What is mean by Program Global Area (PGA)?            It is area in memory that is used by a Single Oracle User Process. 4. What is a data segment?            Data segment are the physical areas within a database block in which the data associated with tables and clusters are stored. 5. What are the factors causing the reparsing of SQL statements in SGA?            Due to insufficient Shared SQL pool size.             Monitor the ratio of the reloads takes place while executing SQL statements.   If   the   ratio   is   greater than 1 then increase the SHARED_POOL_SIZE.             LOGICAL & PHYSICAL ARCHITECTURE OF DATABASE. 6. What is Database Buffers?            Database buffers are cache in the SGA used to hold the data blocks that are read  from  the  data  segments in the database such as tables, indexes and clusters DB_BLOCK_BUFFERS parameter in INIT.ORA decides the size. 7. What is dictionary cache?            Dictionary cache is information about the databse objects stored in a data dictionary table. 8. What is meant by recursive hints?            Number of times processes repeatedly query the dictionary table is called recursive hints.  It is due to the data dictionary cache is too small. By increasing the SHARED_POOL_SIZE parameter we can optimize the size of Data Dictionary Cache. 9. What is meant by redo log buffer?            Change made to entries is written to the on-line redo log files. So that they can be used in roll forward operations during database recoveries. Before writing  them  into  the redo log files, they will first brought to redo  log  buffers  in  SGA  and  LGWR  will  write  into files frequently.LOG_BUFFER parameter will decide the size. 10. How will you swap objects into a different table space for an existing database? Export the user             Perform import using the command imp system/manager   file=export.dmp indexfile= newrite.sql. This will create all definitions into newfile.sql. Drop necessary objects.             Run the script newfile.sql after altering the tablespaces. Import from the backup for the necessary objects.  

Concepts and Architecture of Database Structures Part – 4  1. List the Optional Flexible Architecture (OFA) of Oracle database? Or how can we organise the tablespaces in Oracle database to have maximum performance?             SYSTEM - Data dictionary tables.

Page 21: Complete SQL Commands

            DATA - Standard operational tables.            DATA2- Static tables used for standard operations            INDEXES - Indexes for Standard operational tables.            INDEXES1 - Indexes of static tables used for standard operations.            TOOLS - Tools table.            TOOLS1 - Indexes for tools table.            RBS - Standard Operations Rollback Segments,            RBS1, RBS2 - Additional/Special Rollback segments.            TEMP - Temporary purpose tablespace            TEMP_USER - Temporary tablespace for users.            USERS - User tablespace. 2. How will you force database to use particular rollback segment?            SET TRANSACTION USE ROLLBACK SEGMENT rbs_name. 3. What is meant by free extent?            A free extent is a collection of continuous free blocks in tablespace. When a segment is dropped its extents are reallocated and are marked as free. 4. How free extents are managed in Ver. 6.0 and Ver. 7.0?            Free extents cannot be merged together in Ver. 6.0.Free extents are periodically coalesces with the neighboring free extent in Ver. 7.0 5. Which parameter in Storage clause will reduce no. of rows per block?            PCTFREE parameter            Row size also reduces no of rows per block. 6. What is the significance of having storage clause?            We can plan the storage for a table as how much initial extents are required, how much can be extended next, how much % should leave free for managing row updations etc. 7. How does Space allocation table place within a block?Each block contains entries as followsFixied block headerVariable block headerRow Header,row date (multiple rows may exists)PCTEREE (% of  free space for row updation in future) 8. What is the role of PCTFREE parameter is Storage clause?            This is used to reserve certain amount of space in a block for expansion of rows. 9. What is the OPTIMAL parameter?            It is used to set the optimal length of a rollback segment. 10. What is the functionality of SYSTEM table space?            To manage the database level transactions such as modifications of the data dictionary table that record information about the free space usage. 

11. How will you create multiple rollback segments in a database?     Create a database which implicitly creates a SYSTEM Rollback Segment in a SYSTEM tablespace. 12. Create a Second Rollback Segment name R0 in the SYSTEM tablespace.    Make new rollback segment available (After shutdown, modify init.ora file and Start database) Create other tablespaces (RBS) for rollback segments. Deactivate Rollback Segment R0 and activate the newly created rollback segments.

Page 22: Complete SQL Commands

 13. How the space utilization takes place within rollback segments?            It will try to fit the transaction in a cyclic fashion to all existing extents. Once it found an extent is in use then it forced to acquire a new extent (No. of extents is based on the optimal size) 14. Why query fails sometimes?            Rollback segment dynamically extent to handle larger transactions entry loads.             A single transaction may wipeout all available free space in the Rollback Segment Tablespace. This prevents other user using Rollback segments. 15. How will you monitor the space allocation?            By querying DBA_SEGMENT table/view. 16. How will you monitor rollback segment status?Querying the DBA_ROLLBACK_SEGS viewIN USE         - Rollback Segment is on-line.AVAILABLE - Rollback Segment available but not on-line.OFF-LINE - Rollback Segment off-lineINVALID        - Rollback Segment Dropped.NEEDS RECOVERY - Contains data but need recovery or corrupted.PARTLY AVAILABLE - Contains data from an unresolved transaction involving a distributed database. List the sequence of events when a large transaction that exceeds beyond its optimal value when an entry wraps and causes the rollback segment to expand into another extend. Transaction Begins.             An entry is made in the RES header for new transactions entry. Transaction acquires blocks in an extent of RBS             The entry attempts to wrap into second extent. None is available, so that the RBS must extent.             The RBS checks to see if it is part of its OPTIMAL size.            RBS chooses its oldest inactive segment.            Oldest inactive segment is eliminated.            RBS extents            The Data dictionary table for space management is updated.            Transaction Completes. 17. How can we plan storage for very large tables?            Limit the number of extents in the table            Separate Table from its indexes.            Allocate sufficient temporary storage. 18. How will you estimate the space required by non-clustered tables?            Calculate the total header size            Calculate the available dataspace per data block            Calculate the combined column lengths of the average row            Calculate the total average row size.            Calculate the average number rows that can fit in a block            Calculate the number of blocks and bytes required for the table.             After arriving the calculation, add 10 % additional space to calculate the initial extent size for a working table.  19. Is possible to use raw devices as data files and what are the advantages over file. System files?             Yes. 

Page 23: Complete SQL Commands

The advantages over file system files             I/O will be improved because Oracle is bye-passing the kernel which writing into disk.Disk Corruption will be very less. 20. What is a Control file?             Database's overall physical architecture is maintained in a file called control file. It will be used to maintain internal consistency and guide recovery operations. Multiple copies of control files are advisable. 

 21. How to implement the multiple control files for an existing database?             Shutdown the databse            Copy one of the existing control file to new location            Edit Config ora file by adding new control file.name            Restart the database. 22. What is meant by Redo Log file mirrorring ? How it can be achieved?             Process of having a copy of redo log files is called mirroring.             This can be achieved by creating group of log files together, so that LGWR will automatically writes them to all the members of the current on-line redo log group. If any one group fails then database automatically switch over to next group. It degrades performance.  23. What is advantage of having disk shadowing/ Mirroring?            Shadow set of disks save as a backup in the event of disk failure. In most Operating System if any disk failure occurs it automatically switchover to place of failed disk.             Improved performance because most OS support volume shadowing can direct file  I/O request to use the shadow set of files instead of the main set of files. This reduces I/O load on the main set of disks. 24. What is use of Rollback Segments in Database?             They allow the database to maintain read consistency between multiple transactions. 25. What is a Rollback segment entry?             It is the set of before image data blocks that contain rows that are modified by a transaction.Each Rollback Segment entry must be completed within one rollback segment.             A single rollback segment can have multiple rollback segment entries. 26. What is hit ratio?            It is a measure of well the data cache buffer is handling requests for data.             Hit Ratio = (Logical Reads - Physical Reads - Hits Misses)/ Logical Reads. When will be a segment released?             When Segment is dropped.            When Shrink (RBS only)            When truncated (TRUNCATE used with drop storage option) 27. What are disadvanteges of having raw devices?            We should depend on export/import utility for backup/recovery (fully reliable)             The tar command cannot be used for physical file backup, instead we can use dd command which is less flexible and has limited recoveries. 

Page 24: Complete SQL Commands

28. List the factors that can affect the accuracy of the estimations?             The space used transaction entries and deleted records do not become free immediately after completion due to delayed cleanout.             Trailing nulls and length bytes are not stored.             Inserts of, updates to and deletes of rows as well as columns larger than a single datablock, can cause fragmentation a chained row pieces.

 

DATABASE SECURITY & ADMINISTRATION 1. What is user Account in Oracle database?             A user account is not a physical structure in Database but it is having important relationship to the objects in the database and will be having certain privileges. 2. How will you enforce security using stored procedures?             Don't grant user access directly to tables within the application.             Instead grant the ability to access the procedures that access the tables.             When procedure executed it will execute the privilege of procedures owner. Users cannot access tables except via the procedure. 3. What is the dictionary tables used to monitor a database spaces?             DBA_FREE_SPACE             DBA_SEGMENTS             DBA_DATA_FILES.  4. What are the responsibilities of a Database Administrator? Installing and upgrading the Oracle Server and application tools.Allocating system storage and planning future storage requirements for the database system.Managing primary database structures (tablespaces)Managing primary objects (table,views,indexes)Enrolling users and maintaining system security.Ensuring compliance with Oralce license agreementControlling and monitoring user access to the database.Monitoring and optimising the performance of the database.Planning for backup and recovery of database information.Maintain archived data on tapeBacking up and restoring the database.Contacting Oracle Corporation for technical support. 5. What are the roles and user accounts created automatically with the database?             DBA - role contains all database system privileges.             SYS user account - The DBA role will be assigned to this account. All of the basetables and views for the database's dictionary are store in this schema and are manipulated only by ORACLE.             SYSTEM user account - It has all the system privileges for the database and additional  tables  and  views  that display administrative information and internal  tables  and  views  used  by  oracle tools are created using this username. 6. What are the database administrator’s utilities available?             SQL * DBA - This allows DBA to monitor and control an ORACLE database.

Page 25: Complete SQL Commands

             SQL * Loader - It loads data from standard operating system files (Flat files) into ORACLE database tables.             Export (EXP) and Import (imp) utilities allow you to move existing data in ORACLE format to and from ORACLE database. 7. What are the minimum parameters should exist in the parameter file (init.ora)?             DB NAME - Must set to a text string of no more than 8 characters and it will  be  stored inside the datafiles, redo log files and control files and control file while database creation.             DB_DOMAIN - It is string that specifies the network domain where the database  is  created. The global database name is identified by setting these parameters (DB_NAME & DB_DOMAIN)             CONTORL FILES - List of control filenames of the database. If name is not mentioned then default name will be used.             DB_BLOCK_BUFFERS - To determine the no of buffers in the buffer cache in SGA.             PROCESSES - To determine number of operating system processes that can be connected to ORACLE concurrently. The value should be 5 (background process) and additional 1 for each user. ROLLBACK_SEGMENTS - List of rollback segments an ORACLE instance acquires at database startup.             Also optionally LICENSE_MAX_SESSIONS, LICENSE_SESSION_WARNING and LICENSE_MAX_USERS. 9. What is a trace file and how is it created?             Each server and background process can write an associated trace file. When an   internal error is detected by a process or user process, it dumps information about the error to its trace. This can be used for tuning the database. What are roles? How can we implement roles?             Roles are the easiest way to grant and manage common privileges needed by different groups of database users.             Creating roles and assigning provides to roles.             Assign each role to group of users. This will simplify the job of assigning privileges to individual users.

Concepts and Architecture of Database Structures Part - 5  1. What are the steps to switch a database's archiving mode between NO ARCHIVELOG and ARCHIVELOG mode?      1. Shutdown the database instance.     2. Backup the databse     3. Perform any operating system specific steps (optional)     4. Start up a new instance and mount but do not open the databse.     5. Switch the databse's archiving mode. 2. How can you enable automatic archiving? Shut the database

Page 26: Complete SQL Commands

Backup the databaseModify/Include LOG_ARCHIVE_START_TRUE in init.ora file.Start up the databse. 3. How can we specify the Archived log file name format and destination ?             By setting the following values in init.ora file.             LOG_ARCHIVE_FORMAT = arch %S/s/T/tarc (%S - Log sequence number and is zero left  paded,  %s  -  Log  sequence number  not  padded. %T - Thread number lef-zero-paded  and  %t -  Thread number not padded). The file name created is arch 0001 are if %S is used.LOG_ARCHIVE_DEST = path. 4. What is the use of ANALYZE command? And Define Transaction?             To perform one of these function on an index,table, or cluster:             A Transaction is a logical unit of work that comprises one or more SQL statements executed by a single user.             -  To collect statistics about object used by the optimizer and store them in the data dictionary.            -  To delete statistics about the object used by object from the data dictionary.            - To validate the structure of the object.            - To identify migrated and chained rows of the table or cluster.  

 MANAGING DISTRIBUTED DATABASES. 1. How can we reduce the network traffic?            - Replication of data in distributed environment.            - Using snapshots to replicate data.            - Using remote procedure calls. 2. What are snapshots?            Snapshot is an object used to dynamically replicate data between distribute database at specified time intervals. In ver. 7.0 they are read only. 3. What are the various types of snapshots?            Simple and Complex. 4. Differentiate simple and complex, snapshots?            -  A  simple snapshot is based on a query that does not contains GROUP BY clauses, CONNECT BY clauses, Joins, sub-query or snapshot of operations.            - A complex snapshots contain at least any one of the above. 5. What dynamic data replication?            Updating or Inserting records in remote database through database triggers. It may fail if remote database is having any problem. 6. How can you Enforce Referential Integrity in snapshots?            Time the references to occur when master tables are not in use. Perform the reference the manually immediately locking the master tables. We can join tables in snapshots by creating a complex snapshots that will based on the master tables. 7. What are the options available to refresh snapshots?            COMPLETE - Tables are completely regenerated using the snapshot's query and the master tables every time the snapshot referenced.

Page 27: Complete SQL Commands

            FAST - If simple snapshot used then a snapshot log can be used to send the changes to the snapshot tables.            FORCE - Default value. If possible it performs a FAST refresh; otherwise it will perform a complete refresh. 8. What is snapshot log?            It is a table that maintains a record of modifications to the master table in a snapshot.  It is stored in the same database as master table and is only available for simple snapshots.  It should be created before creating snapshots. 9. When will the data in the snapshot log be used?            We must be able to create a after row trigger on table (i.e., it should be not be already available)            After giving table privileges.            We cannot specify snapshot log name because oracle uses the name of the master table in the name of the database objects that support its snapshot log.            The master table name should be less than or equal to 23 characters.            (The table name created will be MLOGS_tablename, and trigger name will be TLOGS name).10. What are the benefits of distributed options in databases?            Database on other servers can be updated and those transactions can be grouped together with others in a logical unit. Database uses a two phase commit. 

MANAGING BACKUP & RECOVERY1. What are the different methods of backing up oracle database?     - Logical Backups     - Cold Backups     - Hot Backups (Archive log) 2. What is a logical backup?            Logical backup involves reading a set of databse records and writing them into a file. Export utility is used for taking backup and Import utility is used to recover from backup. 3. What is cold backup? What are the elements of it?            Cold backup is taking backup of all physical files after normal shutdown of database.  We need to take.     - All Data files.     - All Control files.     - All on-line redo log files.     - The init.ora file (Optional) 4. What are the different kinds of export backups?            Full back - Complete database            Incremental - Only affected tables from last incremental date/full backup date.            Cumulative backup - Only affected table from the last cumulative date/full backup date. 5. What is hot backup and how it can be taken?            Taking backup of archive log files when database is open. For this the ARCHIVELOG mode should be enabled. The following files need to be backed up. All data files. All  Archive log, redo log files. All control files. 6. What is the use of FILE option in EXP command?            To give the export file name. 7. What is the use of COMPRESS option in EXP command?            Flag to indicate whether export should compress fragmented segments into single extents. 8. What is the use of GRANT option in EXP command?            A flag to indicate whether grants on databse objects will be exported or not. Value is 'Y'  or 'N'. 

Page 28: Complete SQL Commands

9. What is the use of INDEXES option in EXP command?            A flag to indicate whether indexes on tables will be exported. 10. What is the use of ROWS option in EXP command?            Flag to indicate whether table rows should be exported. If 'N' only DDL statements for the databse objects will be created. 11. What is the use of CONSTRAINTS option in EXP command?            A flag to indicate whether constraints on table need to be exported. 12. What is the use of FULL option in EXP command?            A flag to indicate whether full databse export should be performed. 13. What is the use of OWNER option in EXP command?            List of table accounts should be exported. 14. What is the use of TABLES option in EXP command?            List of tables should be exported. 15. What is the use of RECORD LENGTH option in EXP command?            Record length in bytes. 16. What is the use of INCTYPE option in EXP command?            Type export should be performed COMPLETE,CUMULATIVE,INCREMENTAL. 17. What is the use of RECORD option in EXP command?            For Incremental exports, the flag indirects whether a record will be stores data dictionary tables recording the export. 18. What is the use of PARFILE option in EXP command?            Name of the parameter file to be passed for export. 19. What is the use of PARFILE option in EXP command?            Name of the parameter file to be passed for export. 20. What is the use of ANALYSE ( Ver 7) option in  EXP command?            A flag to indicate whether statistical information about the exported objects should be written to export dump file.

 21. What is the use of CONSISTENT (Ver 7) option in EXP command?             A flag to indicate whether a read consistent version of all the exported objects should be maintained. 22. What is use of LOG (Ver 7) option in  EXP command ?             The name of the file which log of the export will be written. 23. What is the use of FILE option in  IMP command ?             The name of the file from which import should be performed. 24. What is the use of SHOW option in IMP command?             A flag to indicate whether file content should be displayed or not. 25. What is the use of IGNORE option in IMP command? 

Page 29: Complete SQL Commands

            A flag to indicate whether the import should ignore errors encounter when issuing CREATE commands. 26. What is the use of GRANT option in IMP command?             A flag to indicate whether grants on database objects will be imported. 27. What is the use of INDEXES option in IMP command?             A flag to indicate whether import should import index on tables or not. 28. What is the use of ROWS option in IMP command?             A flag to indicate whether rows should be imported. If this is set to 'N' then only DDL for database objects will be exectued. 

 SQL PLUS STATEMENTS 1. What are the types of SQL Statement?             Data Definition Language: CREATE, ALTER, DROP, TRUNCATE, REVOKE, NO AUDIT & COMMIT.            Data Manipulation Language: INSERT, UPDATE, DELETE, LOCK TABLE, EXPLAIN PLAN & SELECT.            Transactional Control: COMMIT & ROLLBACK            Session Control: ALTERSESSION & SET ROLE            System Control: ALTER SYSTEM. 2. What is a transaction ?             Transaction is logical unit between two commits and commit and rollback. 3. What is difference between TRUNCATE & DELETE ?             TRUNCATE commits after deleting entire table i.e., can not be rolled back. Database triggers do not fire on TRUNCATE             DELETE allows the filtered deletion. Deleted records can be rolled back or committed.Database triggers fire on DELETE. 4. What is a join? Explain the different types of joins?             Join is a query which retrieves related columns or rows from multiple tables. Self Join - Joining the table with itself.Equi Join - Joining two tables by equating two common columns.Non-Equi Join - Joining two tables by equating two common columns.Outer  Join  - Joining two tables in such a way that query can also retrive rows that do not have corresponding join value in the other table.             Subquery is a query whose return values are used in filtering conditions of the main query. 5. What is correlated sub-query?             Correlated sub_query is a sub_query which has reference to the main query. 6. Explain Connect by Prior?             Retrives rows in hierarchical order.

Page 30: Complete SQL Commands

EX: select empno, ename from emp where. 7. Difference between SUBSTR and INSTR?             INSTR (String1,String2(n,(m)),            INSTR returns the position of the mth occurrence of the string 2 in string1. The search begins from nth position of string1.             SUBSTR (String1 n,m)            SUBSTR returns a character string of size m in string1, starting from nth postion of string1. 

Concepts and Architecture of Database Structures Part - 6 1. Explain UNION, MINUS, UNION ALL, INTERSECT? INTERSECT returns all distinct rows selected by both queries.MINUS - returns all distinct rows selected by the first query but not by the second.UNION - returns all distinct rows selected by either queryUNION ALL - returns all rows selected by either query, including all duplicates. 2. What is ROWID?             ROWID is a pseudo column attached to each row of a table. It is 18 character long, blockno, rownumber are the components of ROWID. 2.a) What is the fastest way of accessing a row in a table?            Using ROWID  

  CONSTRAINTS 3. What is an Integrity Constraint?           Integrity constraint is a rule that restricts values to a column in a table. 4. What is Referential Integrity?            Maintaining data integrity through a set of rules that restrict the values of one or more columns of the tables based on the values of primary key or unique key of the referenced table. 5. What is the usage of SAVEPOINTS?            SAVEPOINTS are used to subdivide a transaction into smaller parts. It enables rolling back part of a transaction. Maximum of five save points are allowed. 6. What is ON DELETE CASCADE?            When ON DELETE CASCADE is specified ORACLE maintains referential integrity by automatically removing dependent foreign key values if a referenced primary or unique key value is removed. 7. What are the data types allowed in a table?            CHAR, VARCHAR2, NUMBER, DATE, RAW, LONG and LONG RAW. 8. What is difference between CHAR and VARCHAR2? What is the maximum SIZE allowed for each type?            CHAR pads blank spaces to the maximum length. VARCHAR2 does not pad blank spaces. For CHAR it is 255 and 2000 for VARCHAR2. 

Page 31: Complete SQL Commands

9. How many LONG columns are allowed in a table? Is it possible to use LONG columns in WHERE clause or ORDER BY?            Only one LONG columns is allowed. It is not possible to use LONG column in WHERE or ORDER BY clause. 10. What are the pre requisites?I. To modify datatype of a column?ii. To add a column with NOT NULL constraint?             To Modify the datatype of a column the column must be empty.To add a column with NOT NULL constrain, the table must be empty. 11. Where the integrity constraints are stored in Data Dictionary?            The integrity constraints are stored in USER_CONSTRAINTS. 12. How will you a activate/deactivate integrity constraints?            The integrity constraints can be enabled or disabled by ALTER TABLE ENABLE constraint/DISABLE constraint. 13. If an unique key constraint on DATE column is created, will it validate the rows that are inserted with SYSDATE?            It won't, Because SYSDATE format contains time attached with it.  14. What is a database link?            Database Link is a named path through which a remote database can be accessed. 16. How to access the current value and next value from a sequence? Is it possible to access the current value in a session before accessing next value?            Sequence name CURRVAL, Sequence name NEXTVAL.            It is not possible. Only if you access next value in the session, current value can be accessed. 17. What is CYCLE/NO CYCLE in a Sequence ?            CYCLE specifies that the sequence continues to generate values after reaching either maximum or minimum value. After pan ascending sequence reaches its maximum value, it generates its minimum value. After a descending sequence reaches its minimum, it generates its maximum.            NO CYCLE specifies that the sequence cannot generate more values after reaching its maximum or minimum value. 18. What are the advantages of VIEW?            To protect some of the columns of a table from other users.            To hide complexity of a query.            To hide complexity of calculations. 19. Can a view be updated/inserted/deleted? If Yes under what conditions?            A View can be updated/deleted/inserted if it has only one base table if the view is based on columns from one or more tables then insert, update and delete is not possible. 20. If a View on a single base table is manipulated will the changes be reflected on the base table?            If changes are made to the tables which are base tables of a view will the changes be reference on the view. 

 FORMS BASIC 1. What is an SQL *FORMS?            SQL  *forms  is  4GL  tool  for  developing  and  executing;  Oracle  based interactive application.

Page 32: Complete SQL Commands

 2. What is the maximum size of a form?            255 character width and 255 characters  Length. 3. Name the two files that are created when you generate the form give the file extension ?            INP (Source File)            FRM (Executable File) 4. How do you control the constraints in forms?            Select the use constraint property is ON Block definition screen. BLOCK5. Committed block sometimes refer to a BASE TABLE? True or False.            False. 6. Can we create two blocks with the same name in form 3.0?            No. 7. While specifying master/detail relationship between two blocks specifying the join condition is a must? True or False.           True.

Database             A database is a logically coherent collection of data with some inherent meaning, representing some aspect of real world and which is designed, built and populated with data for a specific purpose DBMS 

            It is a collection of programs that enables user to create and maintain a database. In other words it is general-purpose software that provides the users with the processes of defining, constructing and manipulating the database for various applications.

Database system 

            The database and DBMS software together is called as Database system.  Advantages of DBMS?

            Ø Redundancy is controlled.             Ø Unauthorized access is restricted.             Ø providing multiple user interfaces.             Ø Enforcing integrity constraints.             Ø Providing backup and recovery. Disadvantage in File Processing System             Ø Data redundancy & inconsistency.             Ø Difficult in accessing data.             Ø Data isolation.             Ø Data integrity.             Ø Concurrent access is not possible.             Ø Security Problems. The three levels of data abstraction             Ø Physical level: The lowest level of abstraction describes how data are stored.

Page 33: Complete SQL Commands

            Ø Logical level: The next higher level of abstraction, describes what data are stored in database and what relationship among those data.            Ø View level: The highest level of abstraction describes only part of entire database. Data Independence             Data independence means that “the application is independent of the storage structure and access strategy of data”. In other words, The ability to modify the schema definition in one level should not affect the schema definition in the next higher level.

Two types of Data Independence:

            Ø Physical Data Independence: Modification in physical level should not affect the logical level.             Ø Logical Data Independence: Modification in logical level should affect the view level. 

NOTE: Logical Data Independence is more difficult to achieve View & How is it related to data independence?

            A view may be thought of as a virtual table, that is, a table that does not really exist in its own right but is instead derived from one or more underlying base table. In other words, there is no stored file that direct represents the view instead a definition of view is stored in data dictionary. Growth and restructuring of base tables is not reflected in views. Thus the view can insulate users from the effects of restructuring and growth in the database. Hence accounts for logical data independence. 

Data Model 

            A collection of conceptual tools for describing data, data relationships data semantics and constraints.

Prev - Next >>1. Following are the advantages of DBMS?a.Redundancy is controlledb.unauthorized access is restrictedc.Doesnt enforce integrity constraintsd.both a & b 2. levels of data abstraction available?a) 1b)2c) 3d)4 3. The highest level of abstraction describes only part of entire database.a.Physical levelb)logical levelc)view leveld)both b and c 4. A collection of conceptual tools for describing data, data relationships data semantics and constraints.a)data modelb)E-R modelc)object oriented modeld)none 5. This data model is based on real world that consists of basic objects called entities and of relationship among these objectsa)data modelb)E-R modelc)object oriented modeld)none 

Page 34: Complete SQL Commands

6. A 'thing' in the real world with an independent existencea)entityb)modelc)both a and bd)none of these 7. A data base schema that is specified by a set of definitions expressed by a special language is calleda)DDLb)VDLc)DMLd)SDL 8. The language that is used to specify the internal schema isa)DDLb)VDLc)DMLd)SDL 9. The process of analyzing the given relation schemas based on their Functional Dependencies is known asa)Dependencyb)normalizationc)both a and bd)none 10. A relation schema R is in ____ if it is in 1NF and every non-prime attribute, A in R is fully functionally dependent on primary key.a)1 NFb)2 NFc)3 NFd)BCNF 11. A relation schema R is in ____ if it is in 3NF and satisfies an additional constraint that for every FD X A, X must be a candidate keya)1 NFb)2 NFc)3 NFd)BCNF 12. The set of attributes that can uniquely identify weak entities and that are related to same owner entity isa)Partial keyb)alternate keyc)artificial keyd)compound key

 13. All Candidate Keys excluding the Primary Key are known as ___a)Partial keysb)alternate keysc)artificial keysd)compound keys 14. When one of the data elements stored within a construct is utilized as the primary key, then it is called the?a)alternate keyb)natural keyc)compound keyd)partial key 15. The technique for determining how quickly specific data can be found is known as__a)normalization

Page 35: Complete SQL Commands

b)data manipulatingc)indexingd)none of these 16. Number of types of indexinga)1b)4c)5d)2 17. The phase that identifies an efficient execution plan for evaluating a query that has the least estimated cost is referred to asa)query generationb)query optimizationc)dependencyd)redundancy 18. The concept which is used to model a relationship between a collection of entities and relationships...a)atomicityb)aggregationc)deadlockd)both a and b 19. By taking ______, the DBMS can reduce the amount of work to be done during restart in the event of subsequent crashes a)dead lockb)atomicityc)aggregationsd)checkpoints 20. Number of transaction phases availablea)1b)2c)3d)4 21. Concatenation of every row in one relation with every row in anothera)productb)joinc)insertiond)none of these 22. Concatenation of rows from one relation and related rows from another  a)productb)joinc)insertiond)none of these 24. Major sets of files on disk that compose a databasea)database filesb)control filesc)redo logsd)all the above 25. _____is a PL/SQL block that can defined to automatically execute for insert, update, and delete statements against a tablea)databaseb)database triggerc)both a and bd)none of these 

Page 36: Complete SQL Commands

 26. Stored procedures are used to ____a)increase the network trafficb)Remove the network trafficc)reduce the network trafficd)block the network traffic 27. Tables derived from the ERDa) Are totally unnormalisedb) Are always in 1NFc) Can be further denormalisedd) May have multi-valued attributes 28. Spurious tuples may occur due toi. Bad normalizationii. Theta joinsiii. Updating tables from joina) i & ii b) ii & iiic) i & iii d) ii & iii 29. A B C is a set of attributes. The functional dependency is as followsAB -> BAC -> CC -> Ba) is in 1NFb) is in 2NFc) is in 3NFd) is in BCNF 30. In mapping of ERD to DFDa) entities in ERD should correspond to an existing entity/store in DFDb) entity in DFD is converted to attributes of an entity in ERDc) relations in ERD has 1 to 1 correspondence to processes in DFDd) relationships in ERD has 1 to 1 correspondence to flows in DFD 31. A dominant entity is the entitya) on the N side in a 1 : N relationshipb) on the 1 side in a 1 : N relationshipc) on either side in a 1 : 1 relationshipd) nothing to do with 1 : 1 or 1 : N relationship 32. Select 'NORTH', CUSTOMER From CUST_DTLS Where REGION = 'N' Order By CUSTOMER Union Select 'EAST', CUSTOMER From CUST_DTLS Where REGION = 'E' Order By CUSTOMERThe above isa) Not an errorb) Error - the string in single quotes 'NORTH' and 'SOUTH'c) Error - the string should be in double quotesd) Error - ORDER BY clause 33. _____is a program module that provides the interface between the low-level data stored in database, application programs and queries submitted to the systema)storage managerb)buffer managerc)transaction managerd)file manager 34. ____is a program module, which is responsible for fetching data from disk storage into main memory and deciding what data to be cache in memory

Page 37: Complete SQL Commands

a)storage managerb)buffer managerc)transaction managerd)file manager 35. ____is a program module, which ensures that database, remains in a consistent state despite system failures and concurrent transaction execution proceeds without conflictinga)storage managerb)buffer managerc)transaction managerd)file manager 36. _______is a program module, which manages the allocation of space on disk storage and data structure used to represent information stored on a diska)storage managerb)buffer managerc)transaction managerd)file manager

 37. copying the three sets of files (database files, redo logs, and control file) when the instance is shut down is known as ____a)cold backupb)hot backup 38. Which is the subset of SQL commands used to manipulate Oracle Database structures, including   tables?a)DDLb)DMLc)VDLd)DSL 39. What operator performs pattern matching?a)LIKEb)NULLc)NOT NULLd)IS NULL 40. What will be the output of the following query? SELECT DECODE(TRANSLATE('A','1234567890','1111111111'), '1','YES', 'NO' );a)1b)YESc)NOd)YESNO 41. What will be the output of the following query?SELECT REPLACE(TRANSLATE(LTRIM(RTRIM('!! ATHEN !!','!'), '!'), 'AN', '**'),'*','TROUBLE') FROM DUAL;a)TROUBLEb)ATHENTROUBLEc)THETROUBLEd)TROUBLETHETROUBLE

RDBMS Concepts 1. What is database?             A database is a logically coherent collection of data with some inherent meaning, representing some aspect of real world and which is designed, built and populated with data for a specific purpose. 

Page 38: Complete SQL Commands

2. What is DBMS?             It is a collection of programs that enables user to create and maintain a database. In other words it is general-purpose software that provides the users with the processes of defining, constructing and manipulating the database for various applications. 3. What is a Database system?             The database and DBMS software together is called as Database system. 4. Advantages of DBMS?             Redundancy is controlled.            Unauthorized access is restricted.            Providing multiple user interfaces.            Enforcing integrity constraints.            Providing backup and recovery. 5. Disadvantage in File Processing System?             Data redundancy & inconsistency.            Difficult in accessing data.            Data isolation.            Data integrity.            Concurrent access is not possible.            Security Problems. 6. Describe the three levels of data abstraction? There are three levels of abstraction: Physical level: The lowest level of abstraction describes how data are stored. Logical level: The next higher level of abstraction, describes what data are stored in database and what relationship among those data.  View level: The highest level of abstraction describes only part of entire database. 7. Define the "integrity rules" There are two Integrity rules. Entity Integrity: States that “Primary key cannot have NULL value” Referential Integrity: States that “Foreign Key can be either a NULL value or should be Primary Key value of other relation. 8. What is extension and intension? Extension - It is the number of tuples present in a table at any instance. This is time dependent. Intension - It is a constant value that gives the name, structure of table and the constraints laid on it. 9. What is System R? What are its two major subsystems?             System R was designed and developed over a period of 1974-79 at IBM San Jose Research Center. It is a prototype and its purpose was to demonstrate that it is possible to build a Relational System that can be used in a real life environment to solve real life problems, with performance at least comparable to that of existing system.Its two subsystems are            Research Storage            System Relational Data System. 10. How is the data structure of System R different from the relational structure?

Page 39: Complete SQL Commands

             Unlike Relational systems in System R            Domains are not supported            Enforcement of candidate key uniqueness is optional            Enforcement of entity integrity is optional            Referential integrity is not enforced 11. What is Data Independence?                       Data independence means that “the application is independent of the storage structure and access strategy of data”. In other words, The ability to modify the schema definition in one level should not affect the schema definition in the next higher level. Two types of Data Independence: Physical Data Independence: Modification in physical level should not affect the logical level.   Logical Data Independence: Modification in logical level should affect the view level.    NOTE:  Logical Data Independence is more difficult to achieve

 12. What is a view? How it is related to data independence?             A view may be thought of as a virtual table, that is, a table that does not really exist in its own right but is instead derived from one or more underlying base table. In other words, there is no stored file that direct represents the view instead a definition of view is stored in data dictionary. Growth and restructuring of base tables is not reflected in views. Thus the view can insulate users from the effects of restructuring and growth in the database. Hence accounts for logical data independence. 13. What is Data Model?              A collection of conceptual tools for describing data, data relationships data semantics and constraints. 14. What is E-R model?             This data model is based on real world that consists of basic objects called entities and of relationship among these objects. Entities are described in a database by a set of attributes. 15. What is Object Oriented model?             This model is based on collection of objects. An object contains values stored in instance variables with in the              object. An object also contains bodies of code that operate on the object. These bodies of code are called methods. Objects that contain same types of values and the same methods are grouped together into classes. 16. What is an Entity?             It is a 'thing' in the real world with an independent existence. 17. What is an Entity type?                       It is a collection (set) of entities that have same attributes. 18. What is an Entity set?                       It is a collection of all entities of particular entity type in the database. 19. What is an Extension of entity type?             The collections of entities of a particular entity type are grouped together into an entity set. 20. What is Weak Entity set?

Page 40: Complete SQL Commands

             An entity set may not have sufficient attributes to form a primary key, and its primary key compromises of its partial key and primary key of its parent entity, then it is said to be Weak Entity set. 21. What is an attribute?             It is a particular property, which describes the entity. 22. What is a Relation Schema and a Relation?             A relation Schema denoted by R(A1, A2, …, An) is made up of the relation name R and the list of attributes Ai that it contains. A relation is defined as a set of tuples. Let r be the relation which contains set tuples (t1, t2, t3, ..., tn). Each tuple is an ordered list of n-values t=(v1,v2, ..., vn). 23. What is degree of a Relation?             It is the number of attribute of its relation schema. 24. What is Relationship?             It is an association among two or more entities. 25. What is Relationship set?             The collection (or set) of similar relationships. 26. What is Relationship type?               Relationship type defines a set of associations or a relationship set  among a given set of entity types.   27. What is degree of Relationship type?             It is the number of entity type participating.

 28. What is DDL (Data Definition Language)?             A data base schema is specifies by a set of definitions expressed by a special language called DDL. 29. What is VDL (View Definition Language)?             It specifies user views and their mappings to the conceptual schema. 30. What is SDL (Storage Definition Language)?             This language is to specify the internal schema. This language may specify the mapping between two schemas. 31. What is Data Storage - Definition Language?             The storage structures and access methods used by database system are specified by a set of definition in a special type of DDL called data storage-definition language. 32. What is DML (Data Manipulation Language)?             This language that enable user to access or manipulate data as organised by appropriate data model. Procedural DML or Low level: DML requires a user to specify what data are needed and how to get those data. Non-Procedural DML or High level:  DML requires a user to specify what data are needed without specifying how to get those data.

Page 41: Complete SQL Commands

 33. What is DML Compiler?             It translates DML statements in a query language into low-level instruction that the query evaluation engine can understand. 34. What is Query evaluation engine?             It executes low-level instruction generated by compiler. 35. What is DDL Interpreter?             It interprets DDL statements and record them in tables containing metadata. 36. What is Record-at-a-time?             The Low level or Procedural DML can specify and retrieve each record from a set of records. This retrieve of a record is said to be Record-at-a-time. 37. What is Set-at-a-time or Set-oriented?                       The High level or Non-procedural DML can specify and retrieve many records in a single DML statement. This retrieve of a record is said to be Set-at-a-time or Set-oriented. 38. What is Relational Algebra?             It is procedural query language. It consists of a set of operations that take one or two relations as input and produce a new relation. 39. What is Relational Calculus?             It is an applied predicate calculus specifically tailored for relational databases proposed by E.F. Codd. E.g. of languages based on it are DSL ALPHA, QUEL. 40. How does Tuple-oriented relational calculus differ from domain-oriented relational calculus             The tuple-oriented calculus uses a tuple variables i.e., variable whose only permitted values are tuples of that relation. E.g. QUEL             The domain-oriented calculus has domain variables i.e., variables that range over the underlying domains instead of over relation. E.g. ILL, DEDUCE. 41. What is normalization?             It is a process of analysing the given relation schemas based on their Functional Dependencies (FDs) and primary key to achieve the properties            Minimizing redundancy            Minimizing insertion, deletion and update anomalies.   42. What is Functional Dependency?   

            A Functional dependency is denoted by X     Y between two sets of attributes X and Y that are subsets of R specifies a

constraint on the possible tuple that can form a relation state r of R. The constraint is for any two tuples t1 and t2 in r if t1[X] = t2[X] then they have t1[Y] = t2[Y]. This means the value of X component of a tuple uniquely determines the value of component Y.

43. When is a functional dependency F said to be minimal?             Every dependency in F has a single attribute for its right hand side. We cannot replace any dependency X->A in F with a dependency Y->A where Y is a proper subset of X and still have a set of dependency that is equivalent to F. We cannot remove any dependency from F and still have set of dependency that is equivalent to F. 

Page 42: Complete SQL Commands

44. What is Multivalued dependency?             Multivalued dependency denoted by X->->Y specified on relation schema R, where X and Y are both subsets of R, specifies the following constraint on any relation r of R: if two tuples t1 and t2 exist in r such that t1[X] = t2[X] then t3 and t4 should also exist in r with the following propertiest3[x] = t4[X] = t1[X] = t2[X]t3[Y] = t1[Y] and t4[Y] = t2[Y]t3[Z] = t2[Z] and t4[Z] = t1[Z] where [Z = (R-(X U Y)) ]            45. What is Lossless join property?             It guarantees that the spurious tuple generation does not occur with respect to relation schemas after decomposition. 46. What is 1 NF (Normal Form)?             The domain of attribute must include only atomic (simple, indivisible) values. 47. What is Fully Functional dependency?             It is based on concept of full functional dependency. A functional dependency X ->Y is full functional dependency if removal of any attribute A from X means that the dependency does not hold any more. 48. What is 2NF?             A relation schema R is in 2NF if it is in 1NF and every non-prime attribute A in R is fully functionally dependent on primary key. 49. What is 3NF?             A relation schema R is in 3NF if it is in 2NF and for every FD X->A either of the following is trueX is a Super-key of R.A is a prime attribute of R.In other words, if every non prime attribute is non-transitively dependent on primary key. 50. What is BCNF (Boyce-Codd Normal Form)?            A relation schema R is in BCNF if it is in 3NF and satisfies an additional constraint that for every FD X->A, X must be a candidate key.      51. What is 4NF?             A relation schema R is said to be in 4NF if for every Multivalued dependency X->->Y that holds over R, one of following is trueX is subset or equal to (or) XY = R.X is a super key. 52. What is 5NF?             A Relation schema R is said to be 5NF if for every join dependency  {R1, R2, ..., Rn} that holds R, one the following is trueRi = R for some i.The join dependency is implied by the set of FD, over R in which the left side is key of R.   53. What is Domain-Key Normal Form?             A relation is said to be in DKNF if all constraints and dependencies that should hold on the the constraint can be enforced by simply enforcing the domain constraint and key constraint on the relation. 54. What are partial, alternate,, artificial, compound and natural key? Partial Key: It is a set of attributes that can uniquely identify weak entities and that are related to same owner entity. It is sometime called as Discriminator. Alternate Key: All Candidate Keys excluding the Primary Key are known as Alternate Keys.

Page 43: Complete SQL Commands

 Artificial Key: If no obvious key, either stand alone or compound is available, then the last resort is to simply create a key, by assigning a unique number to each record or occurrence. Then this is known as developing an artificial key. Compound Key: If no single data element uniquely identifies occurrences within a construct, then combining multiple elements to create a unique identifier for the construct is known as creating a compound key. Natural Key:  When one of the data elements stored within a construct is utilized as the primary key, then it is called the natural key. 55. What is indexing and what are the different kinds of indexing?             Indexing is a technique for determining how quickly specific data can be found.Types:                        Binary search style indexing                        B-Tree indexing                        Inverted list indexing                        Memory resident table                        Table indexing

56. What is system catalog or catalog relation? How is better known as?            A RDBMS maintains a description of all the data that it contains, information about every relation and index that it contains. This information is stored in a collection of relations maintained by the system called metadata. It is also called data dictionary. 57. What is meant by query optimization?             The phase that identifies an efficient execution plan for evaluating a query that has the least estimated cost is referred to as query optimization. 58. What is join dependency and inclusion dependency? Join Dependency: A Join dependency is generalization of Multivalued dependency.A JD {R1, R2, ..., Rn} is said to hold over a relation R if R1, R2, R3, ..., Rn is a lossless-join decomposition of R . There is no set of sound and complete inference rules for JD. Inclusion Dependency: An Inclusion Dependency is a statement of the form that some columns of a relation are contained in other columns. A foreign key constraint is an example of inclusion dependency. 59. What is durability in DBMS?             Once the DBMS informs the user that a transaction has successfully completed, its effects should persist even if the system crashes before all its changes are reflected on disk. This property is called durability. 60. What do you mean by atomicity and aggregation? Atomicity: Either all actions are carried out or none are. Users should not have to worry about the effect of incomplete transactions. DBMS ensures this by undoing the actions of incomplete transactions. Aggregation:  A concept which is used to model a relationship between a collection of entities and relationships. It is used when we need to express a relationship among relationships. 61. What is a Phantom Deadlock?             In distributed deadlock detection, the delay in propagating local information might cause the deadlock detection algorithms to identify deadlocks that do not really exist. Such situations are called phantom deadlocks and they lead to unnecessary aborts. 62. What is a checkpoint and When does it occur?             A Checkpoint is like a snapshot of the DBMS state. By taking checkpoints, the DBMS can reduce the amount of work to be done during restart in the event of subsequent crashes. 63. What are the different phases of transaction?

Page 44: Complete SQL Commands

 Different phases are            Analysis phase            Redo Phase            Undo phase 64. What do you mean by flat file database?             It is a database in which there are no programs or user access languages. It has no cross-file capabilities but is user-friendly and provides user-interface management. 65. What is "transparent DBMS"?             It is one, which keeps its Physical Structure hidden from user. 66. Brief theory of Network, Hierarchical schemas and their properties             Network schema uses a graph data structure to organize records example for such a database management system is CTCG while a hierarchical schema uses a tree data structure example for such a system is IMS. 67. What is a query?                       A query with respect to DBMS relates to user commands that are used to interact with a data base. The query language can be classified into data definition language and data manipulation language. 68. What do you mean by Correlated subquery?                       Subqueries, or nested queries, are used to bring back a set of rows to be used by the parent query. Depending on how the subquery is written, it can be executed once for the parent query or it can be executed once for each row returned by the parent query. If the subquery is executed for each row of the parent, this is called a correlated subquery.             A correlated subquery can be easily identified if it contains any references to the parent subquery columns in its WHERE clause. Columns from the subquery cannot be referenced anywhere else in the parent query. The following example demonstrates a non-correlated subquery. E.g. Select * From CUST Where '10/03/1990' IN (Select ODATE From ORDER Where CUST.CNUM = ORDER.CNUM) 69. What are the primitive operations common to all record management systems?             Addition, deletion and modification. 70. Name the buffer in which all the commands that are typed in are stored                       ‘Edit’ Buffer 71. What are the unary operations in Relational Algebra?                       PROJECTION and SELECTION. 72. Are the resulting relations of PRODUCT and JOIN operation the same?                       No.            PRODUCT: Concatenation of every row in one relation with every row in another.            JOIN: Concatenation of rows from one relation and related rows from another.

 73. What is RDBMS KERNEL?             Two important pieces of RDBMS architecture are the kernel, which is the software, and the data dictionary, which consists of the system-level data structures used by the kernel to manage the database

Page 45: Complete SQL Commands

You might think of an RDBMS as an operating system (or set of subsystems), designed specifically for controlling data access; its primary functions are storing, retrieving, and securing data. An RDBMS maintains its own list of authorized users and their associated privileges; manages memory caches and paging; controls locking for concurrent resource usage; dispatches and schedules user requests; and manages space usage within its table-space structures 74. Name the sub-systems of a RDBMS             I/O, Security, Language Processing, Process Control, Storage Management, Logging and Recovery, Distribution Control, Transaction Control, Memory Management, Lock Management 75. Which part of the RDBMS takes care of the data dictionary? How             Data dictionary is a set of tables and database objects that is stored in a special area of the database and maintained exclusively by the kernel. 76. What is the job of the information stored in data-dictionary?             The information in the data dictionary validates the existence of the objects, provides access to them, and maps the actual physical storage location. 

77. Not only RDBMS takes care of locating data it also             determines an optimal access path to store or retrieve the data 78. How do you communicate with an RDBMS?             You communicate with an RDBMS using Structured Query Language (SQL) 79. Define SQL and state the differences between SQL and other conventional programming Languages             SQL is a nonprocedural language that is designed specifically for data access operations on normalized relational database structures. The primary difference between SQL and other conventional programming languages is that SQL statements specify what data operations should be performed rather than how to perform them. 80. Name the three major set of files on disk that compose a database in Oracle There are three major sets of files on disk that compose a database. All the files are binary.  These areDatabase filesControl filesRedo logs            The most important of these are the database files where the actual data resides. The control files and the redo logs support the functioning of the architecture itself. All three sets of files must be present, open, and available to Oracle for any data on the database to be useable. Without these files, you cannot access the database, and the database administrator might have to recover some or all of the database using a backup, if there is one. 81. What is an Oracle Instance?             The Oracle system processes, also known as Oracle background processes, provide functions for the user processes—functions that would otherwise be done by the user processes themselvesOracle database-wide system memory is known as the SGA, the system global area or shared global area. The data and control structures in the SGA are shareable, and all the Oracle background processes and user processes can use them. The combination of the SGA and the Oracle background processes is known as anOracle instance 82. What are the four Oracle system processes that must always be up and running for the database to be useable             The four Oracle system processes that must always be up and running for the database to be useable include DBWR (Database Writer), LGWR (Log Writer), SMON (System Monitor), and PMON (Process Monitor). 

Page 46: Complete SQL Commands

RDBMS Concepts Part - 2 1. What are database files, control files and log files. How many of these files should a database have at least? Why? Database Files             The database files hold the actual data and are typically the largest in size. Depending on their sizes, the tables (and other objects) for all the user accounts can go in one database file—but that's not an ideal situation because it does not make the database structure very flexible for controlling access to storage for different users, putting the database on different disk drives, or backing up and restoring just part of the database.                       You must have at least one database file but usually, more than one files are used. In terms of accessing and using the data in the tables and other objects, the number (or location) of the files is immaterial. The database files are fixed in size and never grow bigger than the size at which they were created Control Files             The control files and redo logs support the rest of the architecture. Any database must have at least one control file, although you typically have more than one to guard against loss. The control file records the name of the database, the date and time it was created, the location of the database and redo logs, and the synchronization information to ensure that all three sets of files are always in step. Every time you add a new database or redo log file to the database, the information is recorded in the control files. Redo Logs             Any database must have at least two redo logs. These are the journals for the database; the redo logs record all changes to the user objects or system objects. If any type of failure occurs, the changes recorded in the redo logs can be used to bring the database to a consistent state without losing any committed transactions. In the case of non-data loss failure, Oracle can apply the information in the redo logs automatically without intervention from the DBA.The redo log files are fixed in size and never grow dynamically from the size at which they were created. 2. What is ROWID?             The ROWID is a unique database-wide physical address for every row on every table. Once assigned (when the row is first inserted into the database), it never changes until the row is deleted or the table is dropped. The ROWID consists of the following three components, the combination of which uniquely identifies the physical storage location of the row. Oracle database file number, which contains the block with the rows Oracle block address, which contains the rowThe row within the block (because each block can hold many rows)The ROWID is used internally in indexes as a quick means of retrieving rows with a particular key value. Application developers also use it in SQL statements as a quick way to access a row once they know the ROWID 3. What is Oracle Block? Can two Oracle Blocks have the same address?             Oracle "formats" the database files into a number of Oracle blocks when they are first created—making it easier for the RDBMS software to manage the files and easier to read data into the memory areas.The block size should be a multiple of the operating system block size. Regardless of the block size, the entire block is not available for holding data; Oracle takes up some space to manage the contents of the block. This block header has a minimum size, but it can grow.These Oracle blocks are the smallest unit of storage. Increasing the Oracle block size can improve performance, but it should be done only when the database is first created.Each Oracle block is numbered sequentially for each database file starting at 1. Two blocks can have the same block address if they are in different database files. 4. What is database Trigger?             A database trigger is a PL/SQL block that can defined to automatically execute for insert, update, and delete statements against a table. The trigger can e defined to execute once for the entire statement or once for every row that is inserted, updated, or deleted. For any one table, there are twelve events for which you can define database triggers. A database trigger can call database procedures that are also written in PL/SQL. 5. Name two utilities that Oracle provides, which are use for backup and recovery. 

Page 47: Complete SQL Commands

            Along with the RDBMS software, Oracle provides two utilities that you can use to back up and restore the database. These utilities are Export and Import.The Export utility dumps the definitions and data for the specified part of the database to an operating system binary file. The Import utility reads the file produced by an export, recreates the definitions of objects, and inserts the dataIf Export and Import are used as a means of backing up and recovering the database, all the changes made to the database cannot be recovered since the export was performed. The best you can do is recover the database to the time when the export was last performed.

 6. What are stored-procedures? And what are the advantages of using them.             Stored procedures are database objects that perform a user defined operation. A stored procedure can have a set of compound SQL statements. A stored procedure executes the SQL commands and returns the result to the client. Stored procedures are used to reduce network traffic. 7. How are exceptions handled in PL/SQL? Give some of the internal exceptions' name                       PL/SQL exception handling is a mechanism for dealing with run-time errors encountered during procedure execution. Use of this mechanism enables execution to continue if the error is not severe enough to cause procedure termination.The exception handler must be defined within a subprogram specification. Errors cause the program to raise an exception with a transfer of control to the exception-handler block. After the exception handler executes, control returns to the block in which the handler was defined. If there are no more executable statements in the block, control returns to the caller.User-Defined ExceptionsPL/SQL enables the user to define exception handlers in the declarations area of subprogram specifications. User accomplishes this by naming an exception as in the following example:                        ot_failure  EXCEPTION;In this case, the exception name is ot_failure. Code associated with this handler is written in the EXCEPTION specification area as follows:EXCEPTION      when OT_FAILURE then        out_status_code := g_out_status_code;        out_msg         := g_out_msg;The following is an example of a subprogram exception:EXCEPTION      when NO_DATA_FOUND then        g_out_status_code := 'FAIL';        RAISE ot_failure;Within this exception is the RAISE statement that transfers control back to the ot_failure exception handler. This technique of raising the exception is used to invoke all user-defined exceptions.System-Defined ExceptionsExceptions internal to PL/SQL are raised automatically upon error. NO_DATA_FOUND is a system-defined exception. Table below gives a complete list of internal exceptions. PL/SQL internal exceptions. Exception Name Oracle ErrorCURSOR_ALREADY_OPEN ORA-06511DUP_VAL_ON_INDEX ORA-00001INVALID_CURSOR ORA-01001INVALID_NUMBER ORA-01722LOGIN_DENIED ORA-01017NO_DATA_FOUND ORA-01403NOT_LOGGED_ON ORA-01012PROGRAM_ERROR ORA-06501STORAGE_ERROR ORA-06500TIMEOUT_ON_RESOURCE ORA-00051TOO_MANY_ROWS ORA-01422TRANSACTION_BACKED_OUT ORA-00061VALUE_ERROR ORA-06502ZERO_DIVIDE ORA-01476 

Page 48: Complete SQL Commands

In addition to this list of exceptions, there is a catch-all exception named OTHERS that traps all errors for which specific error handling has not been established. 8. Does PL/SQL support "overloading"? Explain                       The concept of overloading in PL/SQL relates to the idea that you can define procedures and functions with the same name. PL/SQL does not look only at the referenced name, however, to resolve a procedure or function call. The count and data types of formal parameters are also considered.PL/SQL also attempts to resolve any procedure or function calls in locally defined packages before looking at globally defined packages or internal functions. To further ensure calling the proper procedure, you can use the dot notation. Prefacing a procedure or function name with the package name fully qualifies any procedure or function reference. Tables derived from the ERD            a) Are totally unnormalised            b) Are always in 1NF            c) Can be further denormalised            d) May have multi-valued attributes  

 

  (b) Are always in 1NF Spurious tuples may occur due to       i. Bad normalization       ii. Theta joins     iii. Updating tables from join            a) i & ii                         b) ii & iii            c) i & iii                                    d) ii & iii  (a) i & iii  because  theta joins are joins made on keys that are not primary keys. A B C is a set of attributes. The functional dependency is as follows      AB  ->   B      AC ->    C         C ->    B            a) is in 1NF            b) is in 2NF            c) is in 3NF            d) is in BCNF 

 (a) is in 1NF since (AC)+ = { A, B, C} hence AC is the primary key. Since         C       B is a FD given, where neither C is a Key nor B is

a prime attribute, this it is not in 3NF. Further B is not functionally dependent on key AC thus it is not in 2NF.  Thus the given FDs is in 1NF. In mapping of ERD to DFD            a) entities in ERD should correspond to an existing entity/store in DFD            b) entity in DFD is converted to attributes of an entity in ERD            c) relations in ERD has 1 to 1 correspondence to processes in DFD            d) relationships in ERD has 1 to 1 correspondence to flows in DFD  (a) entities in ERD should correspond to an existing entity/store in DFD A dominant entity is the entity            a) on the N side in a 1 : N relationship            b) on the 1 side in a 1 : N relationship            c) on either side in a 1 : 1 relationship            d) nothing to do with 1 : 1 or 1 : N relationship 

Page 49: Complete SQL Commands

(b) on the 1 side in a 1 : N relationship Select  'NORTH', CUSTOMER From CUST_DTLS Where REGION = 'N' Order ByCUSTOMER Union Select  'EAST', CUSTOMER From CUST_DTLS Where REGION = 'E' Order By CUSTOMERThe above is            a) Not an error            b) Error - the string in single quotes 'NORTH' and 'SOUTH'            c) Error - the string should be in double quotes            d) Error -  ORDER BY clause (d)  Error - the ORDER BY clause. Since ORDER BY clause cannot be used in UNIONS 9. What is Storage Manager?              It is a program module that provides the interface between the low-level data stored in database, application programs and queries submitted to the system.    10. What is Buffer Manager?             It is a program module, which is responsible for fetching data from disk storage into main memory and deciding what data to be cache in memory.  11. What is Transaction Manager?             It is a program module, which ensures that database, remains in a consistent state despite system failures and concurrent transaction execution proceeds without conflicting. 12. What is File Manager?             It is a program module, which manages the allocation of space on disk storage and data structure used to represent information stored on a disk.   13. What is Authorization and Integrity manager?             It is the program module, which tests for the satisfaction of integrity constraint and checks the authority of user to access data.   

14. What are stand-alone procedures?             Procedures that are not part of a package are known as stand-alone because they independently defined. A good example of a stand-alone procedure is one written in a SQL*Forms application. These types of procedures are not available for reference from other Oracle tools. Another limitation of stand-alone procedures is that they are compiled at run time, which slows execution. 15. What are cursors give different types of cursors.             PL/SQL uses cursors for all database information accesses statements. The language supports the use two types of cursorsImplicitExplicit 16. What is cold backup and hot backup (in case of Oracle)? Cold Backup: It is copying the three sets of files (database files, redo logs, and control file) when the instance is shut down. This is a straight file copy, usually from the disk directly to tape. You must shut down the instance to guarantee a consistent copy.If a cold backup is performed, the only option available in the event of data file loss is restoring all the files from the latest backup. All work performed on the database since the last backup is lost. Hot Backup: Some sites (such as worldwide airline reservations systems) cannot shut down the database while making a backup copy of the files. The cold backup is not an available option.So different means of backing up database must be used — the hot backup. Issue a SQL command to indicate to Oracle, on a tablespace-by-tablespace basis, that the files of the tablespace are to backed up. The users can continue to make full use of the files, including making

Page 50: Complete SQL Commands

changes to the data. Once the user has indicated that he/she wants to back up the tablespace files, he/she can use the operating system to copy those files to the desired backup destination.             The database must be running in ARCHIVELOG mode for the hot backup option. If a data loss failure does occur, the lost database files can be restored using the hot backup and the online and offline redo logs created since the backup was done. The database is restored to the most consistent state without any loss of committed transactions. 17. What are Armstrong rules? How do we say that they are complete and/or sound The well-known inference rules for FDs         Reflexive rule : 

                                    If Y is subset or equal to X then X       Y.

Augmentation rule:                                    If X       Y then XZ       YZ.

Transitive rule:                                    If  {X      Y, Y       Z} then X        Z.

Decomposition rule :                                    If X        YZ then X        Y.

Union or Additive rule:                                    If {X       Y, X         Z} then X        YZ.

Pseudo Transitive rule :                                    If {X       Y, WY          Z} then WX         Z.

             Of these the first three are known as Amstrong Rules. They are sound because it is enough if a set of FDs satisfy these three. They are called complete because using these three rules we can generate the rest all inference rules.

18. How can you find the minimal key of relational schema?             Minimal key is one which can identify each tuple of the given relation schema uniquely. For finding the minimal key it is required to find the closure that is the set of all attributes that are dependent on any given set of attributes under the given set of functional dependency. Algo. I Determining X+, closure for X, given set of FDs FSet X+ = XSet Old X+ = X+

For each FD  Y        Z in F and if  Y belongs to X+ then add Z to X+

Repeat steps 2 and 3 until Old X+  = X+

 Algo.II Determining minimal K for relation schema R, given set of FDs FSet K to R that is make K a set of all attributes in RFor each attribute A in KCompute (K – A)+ with respect to FIf  (K – A)+ = R then set K = (K – A)+

 19. What do you understand by dependency preservation?             Given a relation R and a set of FDs F, dependency preservation states that the closure of  the union of the projection of F on each decomposed relation Ri is equal to the closure of F. i.e.,((R1(F))  U … U (Rn(F)))+ =  F+ if decomposition is not dependency preserving, then some dependency is lost in the decomposition. 20. What is meant by Proactive, Retroactive and Simultaneous Update. Proactive Update: The updates that are applied to database before it becomes effective in real world . Retroactive Update: The updates that are applied to database after it becomes effective in real world . Simulatneous Update: The updates that are applied to database at the same time when it becomes effective in real world . 

Page 51: Complete SQL Commands

21. What are the different types of JOIN operations?             Equi Join:  This is the most common type of join which involves only equality comparisions.Oracle Sample Programs  /* Program to insert records into the students table */ declare            v_rno student.rno%type;            v_name student.name%type;            v_marks student.marks%type;begin            v_rno:=&rno;            v_name:='&name';            v_marks:=&marks;             insert into student(rno,name,marks) values(v_rno,v_name,v_marks);            dbms_output.put_line('record has been inserted');END;/  /* Updating data in the table by entering the roll no of a particular student. */ declare            v_marks student.marks%type;            v_rno student.rno%type;begin            select marks,rno into v_marks,v_rno from student where rno=&rno;             if  (v_marks >=75) then            update student set grade='Distinction' where rno=v_rno;                       elsif (v_marks >=60 and v_marks < 75) then            update student set grade='Credit' where rno=v_rno;                       elsif (v_marks >=40 and v_marks < 60) then            update student set grade='Pass' where rno=v_rno;             else                       update student set grade='Fail' where rno=v_rno;            end if;END;//* Get emp details */ declare            v_ename emp.ename%type;            v_sal emp.salary%type;begin            select ename,salary into v_ename,v_sal from emp where empno=&empno;            dbms_output.put_line('your name is '||v_ename);            dbms_output.put_line('you are getting ' ||v_sal ||' dollars');exception

Page 52: Complete SQL Commands

            when No_data_found then                         dbms_output.put_line('No such employee present');            when too_many_rows then                        dbms_output.put_line('Too many records found');end;/ declare            mrec emp%rowtype;begin            select ename,salary into mrec.ename,mrec.salary from emp where empno=&empno;            dbms_output.put_line('your name is '||mrec.ename);            dbms_output.put_line('you are getting ' ||mrec.salary ||' dollars');exception            when No_data_found then                         dbms_output.put_line('No such employee present');            when too_many_rows then                        dbms_output.put_line('Too many records found');end;/ declare            x number;begin            for x in 1..10            loop            dbms_output.put_line(x);            end loop;end; /

  declare            x number:=1;begin            while(x<=10)            loop            dbms_output.put_line(x);            x:=x+1;            end loop;end;/ Declare            x number:=2;begin            loop            dbms_output.put_line(x);            x:=x+2;

Page 53: Complete SQL Commands

            exit when x = 22;            end loop;END;/ declare            eng number;            maths number;            science number;            total number;            per number;begin            eng:=&englishmarks;            maths:=&mathsmarks;            science:=&sciencemarks;            total:=eng+maths+science;            per:=total/3;             if(per >= 75) then                        dbms_output.put_line('Distinction');            elsif (per >=60 and per <75) then                        dbms_output.put_line('Credit');            elsif (per >=40 and per <60) then                        dbms_output.put_line('Pass');            else                        dbms_output.put_line('Fail');            end if;end;/ declare            eng number;            maths number;            science number;            total number;            per number;begin            eng:=&englishmarks;            maths:=&mathsmarks;            science:=&sciencemarks;            total:=eng+maths+science;            per:=total/3;             if(per >= 75) then                        dbms_output.put_line('Distinction');            else if (per >=60 and per <75) then                        dbms_output.put_line('Credit');            else if (per >=40 and per <60) then                        dbms_output.put_line('Pass');            else                        dbms_output.put_line('Fail');            end if;

Page 54: Complete SQL Commands

            end if;            end if;end;/ 

CURSORS declare            cursor c1 is select empno,ename,salary from emp order by empno desc;            mrec emp%rowtype;begin            open c1;            for i in 1..2            loop            fetch c1 into mrec.empno,mrec.ename, mrec.salary;            insert into empdup(empno,ename,salary) values(mrec.empno,mrec.ename, mrec.salary);            exit when c1%notfound;            end loop;            close c1;end;/ /* Program to copy 'n' records to another table using  %rowcount */ DECLARE            cursor c2 is select empno,ename,salary from emp;            mrec emp%rowtype;BEGIN            open c2;            loop            fetch c2 into mrec.empno,mrec.ename,mrec.salary;            exit when c2%rowcount=&EnterNoOfRows;            insert into empdup(empno,ename,salary) values(mrec.empno,mrec.ename,mrec.salary);            end loop;            close c2;END;/  /* Program to extract top 5 records from the students and insert them into the toppers table */ DECLARE            cursor c1 is select name, grade from student order by marks desc;            mrec student%rowtype;BEGIN            open c1;            loop            fetch c1 into mrec.name,mrec.grade;            exit when c1%rowcount=5;            insert into toppers (name, grade) values(mrec.name,mrec.grade);            end loop;            close c1;

Page 55: Complete SQL Commands

            dbms_output.put_line('Successfully inserted rows in Toppers table');END;/  DECLARE          display first name of women of all ages in the People tableCURSOR Get_Women IS         SELECT First_Name FROM People WHERE Gender = 'F';         Then we OPEN it, FETCH it until the EOF, and CLOSE it. These last three operations are done implicitly by the FOR LOOP --below: BEGIN       FOR Get_Women_cur IN Get_Women LOOP       DBMS_OUTPUT.PUT_LINE(Get_Women_cur.First_Name);END LOOP;END;/ ISOPEN: Boolean - is the cursor open or closed?FOUND: Boolean - did the cursor retrieve a row?NOTFOUND: Boolean - The reverse of FOUND. TRUE when a row could not be retrieved.ROWCOUNT: NUMBER, which row is it? 1st, 2nd, etc. This is not the equivalent of a RecordCount in the dynaset or Recordset. This is actually the current record number.Using these indicators, we can control the loop: DECLARE          display first name of women of all ages in the PEOPLE tableCURSOR Get_Women IS          SELECT First_Name FROM People WHERE Gender = 'F';          Name_Rec Get_Women%ROWTYPE;BEGIN         OPEN Get_Women;         LOOP                  FETCH Get_Women INTO Name_Rec;                  EXIT WHEN Get_Women%NOTFOUND;                  DBMS_OUTPUT.PUT_LINE(Name_Rec.First_Name);         END LOOP;CLOSE Get_Women;END;/

 create or replace procedure pr1(a number, b number) is c number; begin            c:=a+b;            dbms_output.put_line('The sum is :' || c);end;/

Page 56: Complete SQL Commands

 PROCEDURES AND FUNCTIONS

1. Procedure is a subprogram which consists of a set of sql statement.2. Procedures are not very different from functions.3. A procedure or function is a logically grouped set of SQL and PL/SQL statements that perform a specific task.4. A stored procedure or function is a named pl/sql code block that have been compiled and stored in one of the

oracle engines's system tables.5. To make a procedure or function dynamic either of them can be passed parameters before execution.6. A procedure or function can then change the way it works depending upon the parameters passed prior to its

execution.7. Procedures and function are made up of a declarative part, an executable part and an optional exception-

handling part8. A declaration part consists of declarations of variables.9. A executable part consists of the logic i.e. sql statements....and exception handling part handles any error during

run-time             The oracle engine performs the following steps to execute a procedure or function....Verifies user access, Verifies procedure or funtion validity and executes the procedure or function. Some of the advantages of using procedures and functions are: security, performance, memory allocation, productivity, integrity.             Most important the difference between procedures and functions: A function must return a value back to the caller. A function can return only one value to the calling pl/sql block. By defining multiple out parameters in a procedure, multiple values can be passed to the caller. The out variable being global by nature, its value is accessible by any pl/sql code block including the calling pl/sql block. Syntax for stored procedure: CREATE OR REPLACE PROCEDURE [schema] procedure name (argument {IN, OUT, IN OUT} data type, ..) {IS, AS}variable declarations; constant declarations; BEGINpl/sql subprogram body;EXCEPTIONexception pl/sql block;END; Syntax for stored function:

CREATE OR REPLACE FUNCTION[schema] functionname(argument IN data type, ..) RETURN data type {IS, AS}variable declarations; constant declarations; BEGINpl/sql subprogram body;EXCEPTIONexception pl/sql block;END;             The above syntax i think is self explainatory...but i will give u some details...IN : specifies that a value for the argument must be specified when calling the procedure or function. argument : is the name of an argument to the procedure or function. parentheses can be omitted if no arguments are present. OUT : specifies that the procedure passes a value for this argument back to its calling environment after execution. IN OUT : specifies that a value for the argument must be specified when calling the procedure and that the procedure

Page 57: Complete SQL Commands

passes a value for this argument back to its calling environment after execution. By default it takes IN. Data type : is the data type of an argument. PROCEDURE USING NO ARGUMENT..AND USING CURSOR CREATE OR REPLACE PROCEDURE P2 IScursor cur1 is select * from emp;beginfor erec in cur1loopdbms_output.put_line(erec.ename);end loop;end; PROCEDURE USING ARGUMENT CREATE OR REPLACE PROCEDURE ME( X IN NUMBER) ISBEGINdbms_output.put_line(x*x);end; sql> exec me(3);Oracle Practice Programs - 2  FUNCTION using argument CREATE OR REPLACE FUNCTION RMT(X IN NUMBER) RETURN NUMBER ISBEGINdbms_output.put_line(x*x);--return (x*x);end; (make a block like this to run it.....)begindbms_output.put_line(rmt(3));end; CREATE A PROCEDURE THAT DELETE ROWS FROM ENQUIRY WHICH ARE 1 YRS BEFORE Create or replace procedure myprocedure is begindelete from enquiry where YEAR(enquirydate) <= YEAR(sysdate) - 1;end; CREATE A PROCEDURE THAT TAKES ARGUMENT STUDENT NAME AND FIND OUT FEES PAID BY THAT STUDENT CREATE or REPLACE procedure me (namee in varchar) iscursor c1 is select a.feespaiddate from feespaid a, enrollment b, enquiry cwherec.enquiryno = b.enquiryno anda.rollno = b.rollno andc.fname = namee;beginfor erec in c1loopdbms_output.put_line(erec.feespaiddate);

Page 58: Complete SQL Commands

end loop;end; SUM OF 2 NOS CREATE or replace procedure p1 isDeclare a number; b number; c number;Begin a:=50; b:=89; c:=a+b; dbms_output.put_line('Sum of '||a||' and '||b||' is '||c);End; DELETION PROCEDURE create or replace procedure myproc isbegindelete from enquiry where fname='somdutt';end; IN and OUT procedure example Create or replace procedure lest ( a number, b out number) isidentify number;beginselect ordid into identity from item whereitemid = a;if identity < 1000 thenb := 100;end if;end l in out parameter example Create or replace procedure sample ( a in number, b in out number) isidentity number;beginselect ordid, prodid into identity, b from item where itemid=a;if b<600 thenb := b + 100;end if;end; now procedure is called by passing parameter declarea number;b number;beginsample(3000, b)dbms_output.put_line(1th value of b is 11 b);end ; 

 

Page 59: Complete SQL Commands

SIMILAR Example AS BEFORE create or replace procedure getsal( sal1 in out number) isbeginselect sal into sal1 from empwhere empno =  sal1;end ; now use the above in plsql block declaresal1 number := 7999;begingetsal(sal1);dbms_output.put_line('The employee salary is' || sal1);end ;             u can make a procedure and functions similarly.....also if u wanna drop a function then use drop function functionname and for procedure use drop procedure procedurename Here is a procedure that will get the first names of the women: PROCEDURE Get_Women_names IS-- display first name of women of all ages in the People table    CURSOR Get_Women IS            SELECT First_Name FROM People WHERE Gender = 'F';    BEGIN        FOR Get_Women_cur IN Get_Women LOOP            DBMS_OUTPUT.PUT_LINE(Get_Women_cur.First_Name);        END LOOP;    END;/ Here is our equal opportunity first name list: PROCEDURE Get_first_names (p_gender IN People.Gender%TYPE) IS-- display first name of men or women of all ages in the People tableCURSOR Get_people IS               SELECT First_Name FROM People WHERE Gender = p_gender;            Gender_prefix VARCHAR2(14);    BEGIN        IF p_gender = 'M' THEN            Gender_prefix := 'The Men Are:';        ELSE            Gender_prefix := 'The Women Are:';        END IF;        DBMS_OUTPUT.PUT_LINE(gender_prefix);        FOR Get_people_cur IN Get_people LOOP            DBMS_OUTPUT.PUT_LINE(Get_people_cur.First_Name);        END LOOP;    END;/ 

 Functions Here is a procedure that will get the first names of the women: 

Page 60: Complete SQL Commands

PROCEDURE Get_Women_names IS    -- display first name of women of all ages in the People table    CURSOR Get_Women IS            SELECT First_Name FROM People WHERE Gender = 'F';    BEGIN        FOR Get_Women_cur IN Get_Women LOOP            DBMS_OUTPUT.PUT_LINE(Get_Women_cur.First_Name);        END LOOP;    END;/ Here is our equal opportunity first name list: PROCEDURE Get_first_names (p_gender IN People.Gender%TYPE) IS-- display first name of men or women of all ages in the People tableCURSOR Get_people IS               SELECT First_Name FROM People WHERE Gender = p_gender;            Gender_prefix VARCHAR2(14);    BEGIN        IF p_gender = 'M' THEN            Gender_prefix := 'The Men Are:';        ELSE            Gender_prefix := 'The Women Are:';        END IF;        DBMS_OUTPUT.PUT_LINE(gender_prefix);        FOR Get_people_cur IN Get_people LOOP            DBMS_OUTPUT.PUT_LINE(Get_people_cur.First_Name);        END LOOP;    END;/ Function(Definition)             A function is a logically grouped set of SQL and PL/SQL statements that perform a specific task. Function is a named pl/sql code block that have been compiled and stored in one of the oracle engines's system tables.             To make function dynamic parameters can be passed before execution. A function can then change the way it works depending upon the parameters passed prior to its execution. Function is made up of a declarative part, an executable part and an optional exception-handling part. Most important the difference between procedures and functions:==========================================A function must return a value back to the caller.A function can return only one value to the calling pl/sql block.By defining multiple out parameters in a procedure,multiple values can be passed to the caller. Syntax for stored function:=============================CREATE OR REPLACE FUNCTION functionname(argument datatype, ..)RETURN datatype ISvariable declarations;BEGINpl/sql subprogram body;EXCEPTIONexception pl/sql block;END;/

Page 61: Complete SQL Commands

 Creating a function:==================Function to display salary of employees based on empno. create or replace function f1(mempno number) return number is msal number(5); BEGIN            select salary into msal from emp where empno=mempno;            return(msal);END;/ Calling a Function:=================BEGIN            dbms_output.put_line(f1(4));END;/ CREATE OR REPLACE FUNCTION RMT(X NUMBER)RETURN NUMBER ISBEGINdbms_output.put_line(x*x);return (x*x);END;/ Function to update salary by 5000 based on empno create or replace function f2(mempno number) return number is msal number(5);Begin            select salary into msal  from emp where empno=mempno;            msal:=msal+5000;            update emp set salary=msal where empno=mempno;            return (msal);END;/ Function to display the day based on the choice create or replace function f3(mday number) return varchar is display varchar(10);BEGIN            if mday=1 then            display:='Sunday';             elsif mday=2 then            display:='Monday';             elsif mday=3 then            display:='Tuesday';             elsif mday=4 then            display:='Wednesday';             elsif mday=5 then            display:='Thursday';             elsif mday=6 then            display:='Friday';

Page 62: Complete SQL Commands

             elsif mday=7 then            display:='Saturday';             end if;                       return(display);END;/ 

Triggers Trigger contains PL/SQL code which gets executed when any event occurs in the table.E,g; INSERT, UPDATE, DELETE. TRIGGERSTrigger is a stored procedure which is called implicitly by oracle engine whenever a insert, update or delete statement is fired. Advantages of database triggers:---> Data is generated on it's own---> Replicate table can be maintained---> To enforce complex integrity contraints---> To edit data modifications---> To autoincrement a fieldetc..  Trigger always has an action associated with it.Trigger gets fired automatically when any event occurs.Hence, a user need not to execute the Trigger code explicitly.Trigger is always transparent to the user.A table can have many triggers associated with it.In order to create triggers on a table, a user should have the Create Trigger privelege.if not so , then DBA can issue the following command to give the privelege. SQL>GRANT CREATE TRIGGER TO USER;Triggers are more powerful than any referential integrity Constraints.Triggers can be used to enforce business rules.Trigger can't include Transaction Processing Statements. (commit, rollback, savepoint)Only one trigger is possible for any type of DML statement.(INSERT, UPDATE, DELETE) per table Syntax:=======CREATE [OR REPLACE] TRIGGER triggername[before | after][delete | Update | insert ]ON Table[For each row][when condition]Pl/sql block Replace option retains the trigger permissions in order to drop and re-create a trigger with the same name. before means trigger will fire before any DML statmentafter means trigger will fire after any DML statment 

Page 63: Complete SQL Commands

For each row option creates a trigger that will be fired once for each row that is updated.This type of trigger is called ROW LEVEL TRIGGER. if for each row is ommited, then trigger is executed once for that statement. (STATEMENT LEVEL TRIGGER) When - This condition can be specified to further restrict the trigger is executed.Restrictions may include the checks for old and new values. Example:For Each Row     when(old.fees>300)        begin          .........pl/sql statement. "Creating Triggers"---------------------------- Trigger to restrict users if they try to delete any record from the emp table create or replace trigger del_trigger_emp after delete on emp for each rowbeginraise_application_error(-20005,'Sorry cant delete the record');end;/Trigger to restrict users to make any changes to emp table  create or replace trigger trigger_emp after delete or insert or update on emp for each rowbeginraise_application_error(-20005,'Sorry , you are not allowed to any changes to the table');end;/ Trigger to update column data after insert or delete statement create or replace trigger trigger_total_subjects before insert or update on subjects for each rowbegin   :new.total:= :new.eng + :new.maths;   dbms_output.put_line('Total column updated successfully');end;/ Trigger to change the case of letters when any updation or insertion takes place in emp Create or replace trigger change_case_ename before insert or update on emp for each rowbegin        :New.ename := upper(:New.ename);

Page 64: Complete SQL Commands

        :new.desig:=initcap(:new.desig);end;/ Trigger to show the previous, latest and difference in salary after updating emp table create or replace trigger sal_update_triggerafter update on empfor each rowdeclare               sal_diff number(5);Begin            sal_diff := :new.salary - :old.salary;            dbms_output.put_line('the old salary is  '  || :old.salary);            dbms_output.put_line('the new salary is  ' || :new.salary);            dbms_output.put_line('the difference in salary is  ' || sal_diff);End; Trigger to insert data in updations table whenever any update takes place in EMP table CREATE OR REPLACE TRIGGER T1BEFORE update on empfor each row begin            insert into updations values(:old.empno, :old.ename, :old.salary, :old.desig,:old.doj);end;/ A database trigger that allows changes to employee table only during the business hours(i.e. from 10 a.m --to 5.00 p.m.) There is no restriction on viewing data from the table CREATE OR REPLACE TRIGGER Time_Check            BEFORE INSERT OR UPDATE OR DELETE            ON EMPBEGIN            IF TO_NUMBER(TO_CHAR(SYSDATE,'hh24')) < 10 OR                                      TO_NUMBER(TO_CHAR(SYSDATE,'hh24')) >= 17 OR            THEN            RAISE_APPLICATION_ERROR (-20004,'YOU CAN ACCESS ONLY BETWEEN 10 AM TO 5PM ONLY.');            END IF;END;/

  To STICK IN SAL FIELD BY TRIGGER MEANS WHEN  U ENTER GREATER THAN 5000, THEN THIS TRIGGER IS EXECUTED Create or replace trigger check_sal

Page 65: Complete SQL Commands

before insert on empfor each rowwhen (New.sal > 5000);beginraise_application_error(-20000, 'your salary is greater than 5000');end;/ Trigger to insert sysdate into the tran_table when any insertion occurs in test table create or replace trigger insert_date_triggerafter insert on testfor each rowdeclare            systemdate char(12);begin            systemdate := to_char(sysdate);            insert into tran_table (trandate,confirmation) values(systemdate,'Transcation done on this date');end;/ Trigger to insert data in tran table whenever any record is upated, deleted or inserted in emp table CREATE OR REPLACE TRIGGERtrigger1 after insert or  update or delete on emp for each rowdeclare            sdate char(12);begin            sdate :=to_char(sysdate);            if updating then            insert into tran values(sdate,'updating');            elsif inserting then            insert into tran values(sdate,'inserting');            elsif deleting then            insert into tran values(sdate,'deleting');            end if;end;/  "Dropping Triggers" sql>Drop trigger triggername; Drop command drops the trigger definition along with its associated permissions. "Disabling Triggers" Alter Trigger Triggername Disable; sql>Alter trigger trigg1 disable; 

Page 66: Complete SQL Commands

Disabling all the triggers associated with a table sql>alter table emp disable all triggers;  “Enabling Triggers” sql> alter trigger trigg1 enable; Enabling triggers on the table level sql>alter table emp enable all triggers; How to view the information about triggers: SQL>select * From user_objects where object_type='TRIGGER'; SQL>select OBJECT_NAME,OBJECT_TYPE  From user_objects where object_type='TRIGGER'; 

 INVERTING A NUMBER 5639 TO 9365 Declare            given_number varchar(5) := '&enterno';            str_length number(2);            inverted_number varchar(5);Begin            str_length := length(given_number);            For cntr in reverse 1..str_length            loop            inverted_number := inverted_number || substr(given_number, cntr, 1);            end loop;            dbms_output.put_line('The Given no is ' || given_number);            dbms_output.put_line('The inverted number is ' || inverted_number);end;/ SUM OF 100 NUMBERS Declare            a number;            s1 number default 0;Begin            a:=1;            loop                        s1:=s1+a;                        exit when (a=100);                        a:=a+1;            end loop;            dbms_output.put_line('Sum between 1 to 100 is '||s1);

Page 67: Complete SQL Commands

End;/ CALCULATION OF NET SALARYdeclare         basic number;        da number;        hra number;        pf number;        netsalary number;begin         basic:=&basic;        da:=basic * (41/100);        hra:=basic * (15/100);         if (basic < 3000)        then             pf:=basic * (5/100);        elsif (basic >= 3000 and basic <= 5000)        then             pf:=basic * (7/100);        elsif (basic >= 5000 and basic <= 8000)        then             pf:=basic * (8/100);        else             pf:=basic * (10/100);        end if;        netsalary:=basic + da + hra -pf;           dbms_output.put_line('Providend Fund : ' || pf);        dbms_output.put_line('Net salary : ' || netsalary);end;/ EXCEPTION HANDLING             Errors in pl/sql block can be handled...error handling refers to the way we handle the errors in pl/sql block so that no crashing stuff of code takes place...This is exactly the same as we do in C++ or java.There are two type:1. Pre-defined exceptions2. User defined exceptions 

 Examples predefined exceptions: No_data_found            ==   when no rows are returnedCurso_already_open     ==   when a cursor is opened in advanceStorage_error             ==   if memory is damagedProgram_error            ==   internal problem in pl/sqlZero_divide                 ==   divide by zeroinvalid_cursor             ==   if a cursor is not open and u r trying to close itLogin_denied              ==   invalid user name or password

Page 68: Complete SQL Commands

Invalid_number          ==   if u r inserting a string datatype for a number datatype which isalready declaredToo_many_rows         ==   if more rows r returned by select statement SYNTAXbeginsequence of statements;exceptionwhen --exception name thensequence of statements;end; When there is no data returned by rowdeclare            price item.actualprice%type;begin            Select actual price into price from item where qty=888;Exception            when no_data_found then            dbms_output.put_line('item missing');end;/ EXAMPLE OF USER DEFINED EXCEPTIONDECLARE             e_rec emp%ROWTYPE;             e1 EXCEPTION;             sal1 emp.salary%TYPE;BEGIN              SELECT salary INTO sal1 FROM emp WHERE ename = 'aarif';              if sal1 < 5000 THEN              RAISE e1;              sal1:= 8500;              UPDATE emp SET salary = sal1 WHERE ename = 'aarif';             END IF; EXCEPTION              WHEN no_data_found THEN               RAISE_APPLICATION_ERROR ( -20001,'aarif is not there.');              WHEN e1 THEN               RAISE_APPLICATION_ERROR (-20002, 'Less Salary.');END;/ EXAMPLE OF RAISE-APPLICATION-ERROR... THIS IS YOUR OWN ERROR --STATEMENT...U RAISE YOUR OWN ERROR Declare            s1 emp.sal %type;begin            select sal into s1 from emp where ename='Sam';            if(no_data_found) then                        raise_application_error(20001, 'sam is not there');            end if;

Page 69: Complete SQL Commands

            if(s1 > 10000) then                        raise_application_error(20002, 'sam is earing a lot');            end if;            update emp set sal=sal+500 where ename='Sam';end;/INTERESTING Example OF USER DEFINED EXCEPTIONS Declare            zero-price exception;            price number(8);begin            select actualprice into price from item where ordid =400;            if price=0 or price is null then                        raise zero-price;            end if;exception            when zero-price then            dbms_output.put_line('raised xero-price exception');end;/ Creating Types in Oracle create or replace type animal_type as object(breed varchar(20),Name varchar(30),birthdate date,member function Age(birthdate in date) return number,pragma restrict_references(age,WNDS));/ create table zoo_inventory(section varchar(30),animal animal_type);/ create or replace type body animal_type asmember function Age(birthdate date) return number is  begin          return round(sysdate-birthdate);  end;end;/ insert into zoo_inventory values('shephard',animal_type('aust','sheep','12-dec-89')) CREATING ABSTRACT DATATYPES:==============================CREATE OR REPLACE TYPE typename as OBJECT(col1 datatype(size),col2 datatype,

Page 70: Complete SQL Commands

col3 dataype)  Creating an Abstract Datatype Create or replace type book_details_type as OBJECT(author varchar(20),edition number,PrintDate date,Price number);/  Using an Abstract datatype in table creation Create or replace Type book_name_type as OBJECT(bookname varchar(30),details book_details_type);/

Getting the details about Abstract datatype select attr_name,length,attr_type_name from user_type_attrswhere type_name='BOOK_DETAILS_TYPE';/ Creating a Relational-object table using abstract datatype Create Table books(bookcode number,name book_name_type);/ Inserting records in Relational-object table INSERT INTO books VALUES(101,book_name_type('Oracle',book_details_type('sam',1,'12-dec-02',4000))); INSERT INTO books VALUES(102,book_name_type('Access',book_details_type('TataMc',3,'2-apr-02',5000))); INSERT INTO books VALUES(103,book_name_type('SQLserver',book_details_type('Sybex',2,'3-jun-03',6000))); INSERT INTO books VALUES(104,book_name_type('MsOffice',book_details_type('Anthony',1,'12-dec-02',2000)));  Displaying Data from the Relational-object table select books.name from books;

Page 71: Complete SQL Commands

 Example 2:----------------create or replace type details_type as object(job varchar(20),mgr number,hiredate date,sal number,comm number,deptno number);/ create or replace type ename_type as object(ename varchar(20),details details_type);/ select attr_name,length,attr_type_name from user_type_attrswhere type_name='DETAILS_TYPE';CREATE TABLE EMP1(EMPNO NUMBER,ENAME ENAME_TYPE); INSERT INTO EMP1 VALUES(1,ENAME_TYPE('JAMES',DETAILS_TYPE('MGR',NULL,'3-AUG-02',3000,NULL,20))); INSERT INTO EMP1 VALUES(2,ENAME_TYPE('Julius',DETAILS_TYPE('Faculty',NULL,'4-AUG-02',2000,NULL,10))); INSERT INTO EMP1 VALUES(3,ENAME_TYPE('Paul',DETAILS_TYpe('Admin',NULL,'3-apr-02',4000,NULL,20)));

Packages             A package consists of the specification section, where we declare variables, tables and procedures, followed by a package body, where we actually build the procedures. In our example we'll only have one such procedure, but as we said before, we try to put birds of a feather in one cage, and procedures of the same ilk in the same package. We need an array (table) to hold the first names. To declare a table, we have to first define a user type: TYPE table_name IS TABLE OF variable_type INDEX BY BINARY_INTEGER; Here is the first names table: TYPE tbl_fnames IS TABLE OF people.first_name%TYPE INDEX BY BINARY INTEGER; The table is declared in the specification section of the package. In the code below I use the term AS. This is the ADA equivalent of IS. You may use either in PL/SQL. They are the same: PACKAGE Human_Resources AS-- we tell the package that we use a table and which procedure to expect.TYPE tbl_fnames IS TABLE OF people.first_name%TYPE    INDEX BY BINARY_INTEGER;PROCEDURE first_names (p_gender IN people.gender%TYPE, fname OUT tbl_fnames);END Human_Resources; 

Page 72: Complete SQL Commands

-- it is nice to know what we have ended In SQL*PLUS we create or replace the package by doing a CREATE OR REPLACE, and following it by pasting the code. We then type a slash (/) and press enter. Now it is time to build the package body: PACKAGE BODY Human_Resources IS    PROCEDURE first_names (p_gender IN people.gender%TYPE, fname OUT tbl_fnames) IS        CURSOR Get_people IS            SELECT first_name from PEOPLE WHERE Gender = p_gender;        table_index NUMBER := 1;    BEGIN        FOR Get_people_cur IN Get_people LOOP            fname (table_index) := Get_people_cur.first_name;            table_index := table_index + 1;        END LOOP;    END;END;/CREATION             create or replace type supertype as object(A number, B number, member procedure disp, member function MF1( x number, y number) return number) not final; DEFINITION: create or replace type body supertype as member procedure disp asbegin            dbms_output.put_line ('A='||A||'B='||B);end;member function MF1(x number,y number)return number asbegin            return x+y;end;end; DESC SUBTYPE             create or replace type subtype under supertype (overriding member procedure disp, overriding member function MF1( x number,y number) return number); BODY OF SUBTYPE create or replace type body subtype  as overriding member procedure disp asbegin            dbms_output.put_line('B='||B||'A='||A);end;overriding member function MF1(x number, y number) return number asbegin            return x*y;end;end; CALLING THE FUNCTIONS 

Page 73: Complete SQL Commands

declare            sup1 sup_type;            sub1 sub_type;            P number;            Q number;begin            sup1:=super type(10,20);            sub1:=super type(10,20);            sup1.disp;            sub1.disp;            P:=sup1.MF1(10,20);            Q:=sub1.MF1(10,20);            dbms_output.put_line('super type value'||P);            dbms_output.put_line('super type value'||Q);end;

/*RETRIEVING THE FIRST 8 RECORDS OF THE EMP_DUP TABLE BY USING THE CURSORS*/declare            cursor emp_cursor is select empno,ename from emp_dup;            r emp_cursor%rowtype;begin            open emp_cursor;            loop                        fetch emp_cursor into r;                        dbms_output.put_line('THE EMPLOYEE DETAILS WAS'||r.empno||r.ename);                        exit when emp_cursor%rowcount>=8;            end loop;close emp_cursor;end; /*RETRIEVING THE DETAILS OF THE EMPLOYEES WHOSE DEPARTMENT WAS 20 USING THE CURSORS*/ declare            cursor dept_cursor is select * from emp_dup where deptno=20;            r emp_dup%rowtype;begin            open dept_cursor;            loop                        fetch dept_cursor into r;                        dbms_output.put_line('THE EMPLOYEE DETAILS FOR DEPT20 WAS'||r.empno||' '  ||r.ename||' '||r.job||' '||r.sal||r.deptno);                        exit when dept_cursor%rowcount>=5;            end loop;close dept_cursor;end; /*RETRIEVING THE FIRST 10 RECORD OF THE EMPLOYEE TABLE USING CURSORS*/declare            cursor emp_10 is select empno,ename from emp_dup;            r emp_10%rowtype;begin            open emp_10;            loop                        fetch emp_10 into r;                        dbms_output.put_line('THE EMPLOYEE DETAILS WAS'||r.empno||' '||r.ename);

Page 74: Complete SQL Commands

                        exit when emp_10%rowcount>=10;            end loop;            dbms_output.put_line('THE NO OF RECORDS DISPLAYED ARE'||emp_10%rowcount);close emp_10;end;/*RETRIEVING THE EMPLOYEE NUMBER AND NAME OF THE EMPLOYEE TABLE AND INSERTING INTO TEMP_LIST TABLE BY USING CURORS AND RECORDS*/ declare            cursor temp_insert is select empno,ename from emp_dup;            emp_record temp_insert%rowtype;begin            open temp_insert;            loop                        fetch temp_insert into emp_record;                        exit when temp_insert%notfound;                        insert into temp_list(empid,tname) values(emp_record.empno,emp_record.ename);            end loop;close temp_insert;end;

 /*RETRIEVING THE EMPLOYEE RECORDS FOR DEPARTMENT 20 USING CURSOR FORLOOPS*/ declare            cursor emp_cur is select deptno,ename from emp_dup where deptno=20;begin            for emp_record in emp_cur            loop                        dbms_output.put_line('THE EMPLOYEE DETAILS WAS'||emp_record.deptno||' '||emp_record.ename);                        exit when emp_cur%notfound;            end loop;end; /*RETRIEVING THE EMPLOYEE RECORDS FOR DEPARTMENT 20 USING CURSOR FOR LOOP SUBQUERY*/ begin            for emp_rec in (select empno,ename,job,deptno from emp_dup where deptno=20)            loop                        dbms_output.put_line('THE EMPLOYEE DETAILS WAS'||emp_rec.empno||'  ' ||emp_rec.ename||' '||emp_rec.job||'  '||emp_rec.deptno);                        exit when sql%notfound;            end loop;end; /*RETRIEVING THE FIRST FIVE EMPLOYEES WITH A JOB HISTORY*/ declare            cursor emp_job is select * from emp_dup;            r emp_job%rowtype;begin            open emp_job;            loop                        fetch emp_job into r;                        dbms_output.put_line('EMPLOYEE #:'||r.empno||'held the job of' ||r.job||'from'||r.hiredate);                        exit when emp_job%rowcount>5;            end loop;close emp_job;

Page 75: Complete SQL Commands

end; /*a)FIRSTLY CREATE A TOP_DOGS TABLE WITH SALARY AS COLUMNb)USE THE DEFINE COMMAND TO PROVIDE THE VALUE OF n FOR DISPLAYING THETOP EARNERS(n) OF THE COMPANYc)IN A LOOP USE THE iSQL*PLUS SUBSTITUTION PARAMETER CREATED AND GATHER THE SALARIES OF THE TOP n PEOPLE FROM THE EMPLOYEES TABLE.THERE SHOULD BE NO DUPLICATION IN THE SALARIES.IF THE TWO EMPLOYEES EARN THE SAME SALARY,THE SALARY SHOULD BE PICKED UP ONLY ONCEd)STORE THE SALARIES IN THE TOP_DOGS TABLE*/ declare            cursor emp_sal is select distinct sal from emp_dup order by sal desc;            r emp_dup.sal%type;begin            open emp_sal;            loop                        fetch emp_sal into r;                        dbms_output.put_line('THE TOP SALARY WISE'||r);                        insert into top_dogs(salary) values(r);                        exit when emp_sal%rowcount>&order_sal;            end loop;close emp_sal;end; /*UPDATING THE SALARY FOR 10% THOSE SALARIES ARE LESS THAN 3000 BY USING "UPDATE OF" CLAUSE AND WHERE "CURRENT OF" IN THE CURSORS*/ declare            cursor upd_curr is select e.empno,e.ename,e.job,e.sal, d.deptno,d.loc,d.dname from emp e,dept d where e.deptno=d.deptno and d.deptno=30 for update of sal NOWAIT;begin            for emp_rec in upd_curr            loop                        if emp_rec.sal<3000 then                                    update emp set sal=emp_rec.sal*1.10 where current of upd_curr;                        end if;            end loop;end;

 /*FOR GETTING INTO THE DISPLAY OF THE DEPT AND EMP TABLES TOGETHER*/ declare            cursor emp_dept is select d.deptno,d.dname,e.ename,e.job,            e.hiredate,e.sal from emp e,dept_id d where e.deptno=d.deptno;begin            for emp_record in emp_dept            loop                        if emp_record.deptno <>30 then                                    dbms_output.put_line('departmentnumber:'||emp_record.deptno|| 'department name'||emp_record.dname);                        end if;            end loop;            for emp_record in emp_dept            loop                        if emp_record.deptno<>30 then                                                                                          dbms_output.put_line(emp_record.ename||emp_record.job||emp_record. hiredate ||emp_record.sal);                        end if;            end loop;            for emp_record in emp_dept

Page 76: Complete SQL Commands

            loop                        if emp_record.deptno=30 then                                    dbms_output.put_line('departmentnumber:'||emp_record.deptno|| 'department name'||emp_record.dname);                        end if;            end loop;            for emp_record in emp_dept            loop                        if emp_record.deptno=30 then                                    dbms_output.put_line(emp_record.ename||emp_record.job||emp_record. hiredate||emp_record.sal);                        end if;            end loop;end; /*ANOTHER TYPE OF THE SAME ABOVE PROBLEM*/ declare            cursor emp_dept is select distinct d.deptno,d.dname,e.ename,e.job, e.hiredate,e.sal from emp e,dept_id d where e.deptno=d.deptno;            a dept_id.deptno%type;            b dept_id.dname%type;begin            select d.deptno,d.dname into a,b from dept_id d where deptno =10;            dbms_output.put_line('departmentnumber:'||a|| 'department name'||b);            select d.deptno,d.dname into a,b from dept_id d where deptno =20;            dbms_output.put_line('departmentnumber:'||a|| 'department name'||b);            for emp_record in emp_dept            loop                        if emp_record.deptno<>30 then                                    dbms_output.put_line(emp_record.ename||emp_record.job||emp_record. hiredate||emp_record.sal);                        end if;            end loop;            select d.deptno,d.dname into a,b from dept_id d where deptno =30;            dbms_output.put_line('departmentnumber:'||a|| 'department name'||b);            for emp_record in emp_dept            loop                        if emp_record.deptno=30 then                                    dbms_output.put_line(emp_record.ename||emp_record.job||emp_record. hiredate||emp_record.sal);                        end if;            end loop;end;

/*DISPLAYING THE TOP TEN EARNERS OF THE COMPANY BY USING THE CURSORS*/ declare            cursor emp_cur is select * from emp order by sal;            cur emp_dup%rowtype;begin            open emp_cur;            loop                        fetch emp_cur into cur;                        if emp_cur%found then                                    dbms_output.put_line('THE TOP TEN EARNERS OF THE EMPLOYEE TABLE WAS'||cur.ename||cur.sal ||cur.job||cur.deptno);                        end if;                        exit when emp_cur%rowcount=10;            end loop;close emp_cur;end; 

Page 77: Complete SQL Commands

/*UPDATING THE SALARIES BY USING THE CURSORS ACCORDING TO THE JOB-WISE*/ declare            cursor emp_upd is select * from emp_dup where deptno=20;            upd emp_upd%rowtype;begin            open emp_upd;            loop                        fetch emp_upd into upd;                        if upd.sal<2000 and upd.job='CLERK' then                                    delete from emp_dup where SAL<2000 AND JOB='CLERK' AND DEPTNO=20;                        elsif upd.job='MANAGER' then                                    upd.sal:=upd.sal+upd.sal*0.15;                        update emp_dup set sal=upd.sal where deptno=20;                        elsif upd.job='CLERK' then                                    upd.sal:=upd.sal+upd.sal*0.01;                                    update emp_dup set sal=upd.sal where deptno=20;                        /*else                                    upd.sal:=upd.sal+100;                        update emp_dup set sal=upd.sal where deptno=20;*/                        end if;                        exit when emp_upd%notfound;            end loop;            /* if upd.sal<4040 then                        delete from emp_dup where deptno=20;            end if;   */close emp_upd;end; declare            cursor emp_cur is select deptno,min(sal) "minimum" from emp group by deptno;begin            for m in emp_cur            loop                        dbms_output.put_line('the deptno and their minimum salaries was'|| m.deptno||m.minimum);            end loop;close emp_cur;end;

4)declare            cursor emp_print is select * from emp_dup;            c emp_print%rowtype;begin            open emp_print;            loop                        fetch emp_print into c;                        if emp_print%found then                                    dbms_output.put_line('THE EMPLOYEE DETAILS ARE'||c.empno||'  '||c.sal||'  '||c.deptno);                        end if;                        exit when emp_print%notfound;            end loop;end; /*THE FOLLOWING PL/SQL CODE DISPLAYS THE DETAILS OF EMPLOYEES BELONGING TO DEPARTMENT NO10 GETTING SALARY=4000 AND STORES THE DETAILS OF EMPLOYEES BELONGING TO DEPARTMENT NO30 AND GETTING SALARY=4000 IN THE TEMP TABLE*/declare            cursor emp_insert is select empno,ename,sal,deptno from emp_dup where deptno=20 and

Page 78: Complete SQL Commands

            sal=4000;            c1 emp_insert%rowtype;begin            open emp_insert;            loop                        fetch emp_insert into c1;                        insert into temp; values(c1.empno,c1.ename,c1.sal,30);                        exit when emp_insert%notfound;            end loop;close emp_insert;end; /*THE FOLLOWING PROGRAM DISPLAYS THE NAME OF THAT MANAGER WHO HAS JOINED THE ORGANIZATION IN THE YEAR 1981.IF THERE IS NO OUTPUT OR IF THERE IS MORE THAN ONE OUTPUT THEN INSTEAD OF GIVING ERROR THE PROGRAMM WILL GIVE PROPER MESSAGE*/ declare            v_ename varchar2(15);            v_job varchar2(15):='MANAGER';begin            select ename,job into v_ename,v_job from emp_dup where hiredate like '%81' and job=v_job;            dbms_output.put_line('THE JOB AND HIS NAME WAS'||v_ename||v_job);            exception            when no_data_found then            dbms_output.put_line('NO SUCH EMPLOYEE WAS HIRED IN 81');            when too_many_rows then            dbms_output.put_line('MORE THAN ONE EMPLOYEE WAS HIRED IN 81');end;create or replace type vtype1 as object(pno  varchar2(20),pdesc varchar2(20),udm number,price number);

create or replace type vendor1 as table of vtype1;

create table vendor_master (ven_code varchar2(20),ven_name varchar2(20) ,prod_details vendor1)nested table prod_details tore as vtemp;

insert into vendor_master values('v001','HCL',vendor1 (  vtype1('p001','XYZ',5,100), vtype1('p002','ABC', 6,150), vtype1('p003','PQR',7,200)  ));

insert into vendor_master values('v002','WIPRO',vendor1 (  vtype1('p004','XYZ',5,100), vtype1('p005', 'ABC',6,150),  vtype1('p006','PQR',7,200)  ));

About Explicit/Implicit Conversion in Oracle Explicit Conversion             Oracle has provided built-in functions to use for converting one datatype to another. The most commonly used conversion functions are the TO_DATE function, which allows you to convert a CHAR value to a DATE value, and the TO_CHAR function, which allows you to convert from a CHAR value to a DATE value. An explicit conversion occurs when you compare a DATE value to a CHAR value and use the function A Word of Caution about Implicit Conversion             It has always been bad practice to rely on implicit conversions because it can result in poor performance.TO_DATE or TO_CHAR to convert the DATE into a CHAR or the CHAR into a DATE.The following example shows how to accomplish this conversion: Select count(1) From pa_projects_all Where start_date >= to_date(‘01-JAN-2000’,’DD-MON-YYYY’) AND completion_date <= to_date(‘01-JAN-2001’,’DD-MON-YYYY’)

Page 79: Complete SQL Commands

/             This converts the values ‘01-JAN-2000’ and ‘01-JAN-2001’ into a DATE datatype of format ‘dd-mon-yyyy’ and compares it to the value of the start_date column. If a match is made, then the counter is incremented and the results will show how many rows exist that meet the criteria. Implicit Conversion             When you create code that requires conversion of datatypes and you do not use the conversion function, PL/SQL attempts to convert the datatype of a value implicitly. With this feature, you can use literals, variables, and parameters of one datatype while another datatype is expected.             In order to accomplish an implicit conversion, you need only compare one datatype to another. The following two examples accomplish the same task and return the same results, though one is an explicit conversion and the other is implicit. First, the explicit conversion example:Select count(1) From pa_projects_all Where start_date >= to_date(‘01-JAN-2000’,’DD-MON-YYYY’) AND completion_date <= to_date(‘01-JAN-2001’,’DD-MON-YYYY’)/COUNT(1)---------958            The result in this case is the number of projects that started on or before January 1, 2000, and have a completion date on or before the January 1, 2001. As you can see, we actually converted one of the dates and left the other as a CHAR. The implicit conversion yields the same result, as follows: SELECT count(1) FROM pa_projects_all WHERE start_date >= ‘01-JAN-2000’ AND completion_date <= ‘01-JAN-2001’/ COUNT(1)---------958             You can see here that Oracle will convert the data implicitly or allow you to convert the data yourself. Both scenarios return the same results. It is your responsibility to ensure that values are convertible. For instance, PL/SQL can convert the CHAR value ‘01-JAN-2000’ to a DATE value, but it cannot convert the CHAR value ‘TOMORROW’ to a DATE value. Similarly, PL/SQL cannot convert a VARCHAR2 value containing alphabetic characters to a NUMBER value.

1)/*DISPLAYING THE EMPLOYEE DETAILS BY USING PROCEDURE*/ create or replace procedure proc_emp_details(eno in number) as e emp%rowtype;begin            select * into e from emp_dup where empno=eno;            dbms_output.put_line('THE EMPLOYEE DETAILS WAS'||' '||e.empno||' '|| e.ename||' '||e.sal||' '||e.job||' '||e.deptno);exception            when no_data_found then            dbms_output.put_line('NO SUCH EMPLOYEE EXISTS');            when too_many_rows then            dbms_output.put_line('MORE THAN ONE EMPLOYEE EXISTS');end proc_emp_details; SQL> execute proc_emp_details(7900); 2)/*DISPLAYING THE NAME AND UPDATED SALARY WHEN THE EMPLOYEE NUMBER HAS BEEN ENTERED AND IT HAS BEEN DONE BY MEANS OF A PROCEDURE*/

Page 80: Complete SQL Commands

 create or replace procedure proc_in_out(eno in number,name out varchar2,salary out number) as e emp%rowtype;begin            select * into e from emp_dup where empno=eno;            if e.job='MANAGER' then                        e.sal:=e.sal+1000;                        update emp_dup set sal=e.sal where empno=eno;            elsif e.job='CLERK' then                        e.sal:=e.sal+500;                        update emp_dup set sal=e.sal where empno=eno;            else e.sal:=e.sal+800;                        update emp_dup set sal=e.sal where empno=eno;            end if;            name:=e.ename;            salary:=e.sal;end proc_in_out; SQL> variable enam varchar2(30) SQL> variable esal number SQL> execute proc_in_out(7900,:enam,:esal); SQL> print enam; SQL> print esal; 3)/*BY USING PROCEDURE INVOKING THE UPDATED SALARY AND EMPLOYEE NAME BY GIVING THE UPDATED SALARY AS OUT PARAMETER IN WHICH BY SIMPLY GIVING THE EMPLOYEE NUMBER*/ create or replace procedure proc_in_out1(eno in number,name out varchar2,salary in number,saly out number) as e emp%rowtype;begin            select * into e from emp where empno=eno;            if e.job ='MANAGER' then                        e.sal:=e.sal+salary;                        update emp set sal=e.sal where empno=eno;            elsif e.job ='CLERK' then                        e.sal:=e.sal+salary;                        update emp set sal=e.sal where empno=eno;            else                        e.sal:=e.sal+salary;                        update emp set sal=e.sal where empno=eno;            end if;            name:=e.ename;            saly:=e.sal;            exception            when no_data_found then            dbms_output.put_line('NO SUCH EMPLOYEE EXISTS');            when too_many_rows then            dbms_output.put_line('MORE THAN ONE EMPLOYEE EXISTS');end proc_in_out1; SQL> variable enam varchar2(30) SQL> variable esal number SQL> execute proc_in_out1(7900,:enam,2000,:esal); SQL> print enam; SQL> print esal;

Page 81: Complete SQL Commands

 4)/*INCREASING THE SALARY BY 10% ACCORDING TO THE EMPLOYEE ID HAS BEEN PASSED*/ create or replace procedure raise_sal(empid number) as r emp_dup%rowtype;salary number;begin            select * into r from emp_dup where empno=empid;            salary:=r.sal*1.10;            update emp_dup set sal=salary where empno=empid;            dbms_output.put_line('THE UPDATED SALARY WAS'||salary);exception            when no_data_found then            dbms_output.put_line('THERE WAS NO SUCH EMPLOYEE_ID EXISTS');            when too_many_rows then            dbms_output.put_line('MORE THAN ONE EMPLOYEE EXISTS FOR THE SAME EMPLOYEE_ID');end; SQL> execute raise_sal(7369); 5)/*THE PROCEDURE HAS FOUR FORMAL PARAMETERS,ONE OF WHICH WAS IN PARAMETER AND THE OTHER THREE ARE OUT PARAMETERS*/ create or replace procedure proc_in_out(empid in number,name out varchar2,esal out number,ecomm out number) asbegin             select ename,sal,comm into name,esal,ecomm from emp_dup where empno=empid;            dbms_output.put_line('THE EMPLOYEE DETAILS WAS'||' '|| name||' '||esal||' '||ecomm);exception            when no_data_found then            dbms_output.put_line('THERE WAS NO SUCH EMPLOYEE EXISTS');            when too_many_rows then            dbms_output.put_line('MORE THAN ONE EMPLOYEE EXISTS FOR THE SAME             EMPLOYEEID');end proc_in_out; SQL> variable salary number SQL> variable namely varchar2(30) SQL> variable commission number SQL> execute proc_in_out(7369,:namely,:salary,:commission); SQL> print namely SQL> print salary SQL> print commission 6)/*CREATING THE PROCEDURES WITH DEFAULT VALUES*/ create or replace procedure proc_dept(v_deptno in number default 60,v_dname in varchar2 default 'unknown',v_loc in varchar2 default 'HYD') asbegin            insert into dept values(v_deptno,v_dname,v_loc);end proc_dept; SQL> execute proc_dept; 

Page 82: Complete SQL Commands

SQL> select * from dept; SQL> execute proc_dept(50,'credit'); SQL> select * from dept; SQL> execute proc_dept(70,'debit','delhi'); SQL> select * from dept;

  7)/*DECLARING THE SUBPROGRAMM AND GET EXECUTED IN THE PROCEDUREa) THE SUBPROGRAMM INSERT THE VALUES INTO THE LOG_TABLESb) THE PROCEDURE DELETES THE EMPLOYEE TABLE BY PASSING THE EMPLOYEE NUMBERc) BOTH ACTIONS WILL BE DONE AT THE SAME TIME WHEN THE PROCEDURE GETS EXECUTED*/ create or replace procedure insert_del(empid in number) asprocedure proc_insertasbegin            insert into log_tables values(user,sysdate);end proc_insert;begin            delete from emp_dup where empno=empid;proc_insert;end insert_del; SQL> execute insert_del(7369); SQL> select * from log_tables; 8)/*DECLARING THE PROEDURES IN AN ANONYMOUS BLOCKa)THE PROCEDURES UPDATES THE SALARY BY 10% BY PASSING THE EMPLOYEE NUMBERb)THAT PROCEDURES GETS INVOKED IN THE ANONYMOUS BLOCK*/ a)create or replace procedure raise_sal(empid number) as r emp_dup%rowtype;salary number;begin            select * into r from emp_dup where empno=empid;            salary:=r.sal*1.10;            update emp_dup set sal=salary where empno=empid;            dbms_output.put_line('THE UPDATED SALARY WAS'||salary);exception            when no_data_found then            dbms_output.put_line('THERE WAS NO SUCH EMPLOYEE_ID EXISTS');            when too_many_rows then            dbms_output.put_line('MORE THAN ONE EMPLOYEE EXISTS FOR THE SAME EMPLOYEE_ID');end; b)declare            empid number:=7499;begin            aise_sal(empid);end; 9)/*INVOKING THE STORED PROCEDURE FROM A STORED PROCEDUREa) THE INVOKED PROCEURE UPDATED THE SALARY OF THE GIVEN EMPLOYEE NUMBERb) THE STORED PROCEDURE UPDATES ALL THE SALARIES OF ALL THE EMPLOYEENUMBERS BY USING THE CURSORS IN THE STORED PROCEDURES*/

Page 83: Complete SQL Commands

 a)create or replace procedure raise_sal(empid number) as r emp_dup%rowtype;salary number;begin            select * into r from emp_dup where empno=empid;            salary:=r.sal*1.10;            update emp_dup set sal=salary where empno=empid;            dbms_output.put_line('THE UPDATED SALARY WAS'||salary);exception            when no_data_found then            dbms_output.put_line('THERE WAS NO SUCH EMPLOYEE_ID EXISTS');            when too_many_rows then            dbms_output.put_line('MORE THAN ONE EMPLOYEE EXISTS FOR THE SAME EMPLOYEE_ID');end; b)create or replace procedure emp_proc as cursor emp_cur is select empno,ename from emp_dup;begin            for emp_rec in emp_cur            loop                        raise_sal(emp_rec.empno);                        exit when emp_cur%notfound;            end loop;end emp_proc; SQL> execute emp_proc;

 10)/*CREATE A NEW PROCEDURE THAT ADDS THE NEW EMPLOYEE FOR THE EMPLOYEE TABLE*/ create or replace procedure add_emp(v_empno in number,v_ename in varchar2,v_sal in number,v_job in varchar2,v_deptno in number) asbegin            insert into emp_dup(empno,ename,sal,job,deptno)            values(v_empno,v_ename,v_sal,v_job,v_deptno);end add_emp; SQL> execute add_emp(123,'chsr',6000,'manager',50); SQL> select * from emp_dup; 11)/*UPDATING THE JOB BY PASSING THE EMPLOYEE NUMBER AS PARAMETER BY USING THE PROCEDURES*/ create or replace procedure upd_emp(v_empno in number,v_job out varchar2) asbegin            v_job:='president';            update emp_dup set job=v_job where empno=v_empno;end upd_emp; SQL> variable p_job varchar2(30); SQL> execute upd_emp(123,:p_job); SQL> print p_job; 12)/*CREATE A PROCEDURE FOR DELETING THE EMPLOYEE IN THE EMPLOYEE TABLEPASSING EMPNO AS IN PARAMETER*/ create or replace procedure del_emp(empid in number) asbegin            delete from emp_dup where empno=empid;

Page 84: Complete SQL Commands

end; SQL> execute del_emp(123); SQL> select * from emp_dup; 13)/*CREATING THE PROCEDURE SUCH THAT WHEN WE PASSING THE EMPLOYEENUMBER AS IN PARAMETER,THE PROCDURE MUST RETURN THE CORRESPONDINGSALARY AND JOB OF THAT EMPLOYEE NUMBER*/ create or replace procedure quer_emp(empid in number,v_sal out number,v_job out varchar2) asbegin            select sal,job into v_sal,v_job from emp_dup where empno=empid;end quer_emp; SQL> variable esal number SQL> variable ejob varchar2(30); SQL> execute quer_emp(7499,:esal,:ejob); SQL> print esal; SQL> print ejob; 1)/*CREATE A PROCEDURE BY THE NAME INCR AND INCREASE THE SALARY OF ANEMPLOYEE,THE EMPLOYEE NUMBER AND THE AMOUNT TO BE INCREMENTED IS PASSED AS PARAMETERS*/ create or replace procedure incr(emp_id in number,amt in number) as p emp_dup%rowtype;increment_amount number;begin            select * into p from emp_dup where empno=emp_id;            increment_amount:=p.sal+amt;            update emp_dup set sal=increment_amount where empno=emp_id;            dbms_output.put_line('THE INCREMENTED AMOUNT WAS'||increment_amount);            if                        p.sal is null then                        dbms_output.put_line('WE CANNOT UPDATE THE AMOUNT FOR THE EMPLOYEEID');            end if;end incr;

 SQL> execute incr(7369,1000); create or replace procedure get_order_lines(order_number in number,output1 out varchar2) as cursor c2(header_id in number) is select line_number,substr(ordered_item,1,20) item, ordered_quantity,unit_selling_price from oe_order_lines_all oel where HEADER_ID = header_id;line_number number(10);ordered_item varchar2(25);ordered_qty number(10);unit_selling_price number(10);HEADER_ID NUMBER(10); begin SELECT HEADER_ID INTO HEADER_ID FROM OE_ORDEr_HEADERS_ALL WHERE ORDER_NUMBER = ORDER_NUMBER;DBMS_OUTPUT.PUT_LINE(HEADER_ID); open c2(HEADER_ID);loop

Page 85: Complete SQL Commands

            fetch c2 into line_number,ordered_item,ordered_qty,unit_selling_price;            dbms_output.put_line(line_number||' '||ordered_item||' '||ordered_qty||' '||unit_selling_price);            output1:= line_number||' '||ordered_item||' '||ordered_qty||' '||unit_selling_price ;end loop;close c2;exception            when no_data_found then null;end;  var t1 number; create or replace procedure get_header_id(order_number number, output2 out number) isheader_id number(10);ord_number number(10); begin            select order_number into ord_number from dual;            select header_id into header_id from oe_order_headers_all where order_number= ord_number;            dbms_output.put_line(header_id);            output2 := header_id;end; var t1 varchar2(1000); create or replace procedure get_order_lines(header_id in number,output1 out varchar2) ashead_id number(10);line_number number(10);ordered_item varchar2(25);ordered_qty number(10);unit_selling_price number(10);order_amnt number(15); BEGIN            select header_id into head_id from dual;            DBMS_OUTPUT.PUT_LINE(HEAD_ID);            select line_number,substr(ordered_item,1,20)            item,ordered_quantity,unit_selling_price,nvl((ordered_quantity*unit_selling_price),0) Amount into line_number,ordered_item,ordered_qty,unit_selling_price,order_amnt from oe_order_lines_all where header_id = head_id ;            dbms_output.put_line(line_number||' '||ordered_item||' '||ordered_qty||' '||unit_selling_price||' '||order_amnt);            output1:= line_number||' '||ordered_item||' '||ordered_qty||' '||unit_selling_price||' '||order_amnt ;exception            when NO_DATA_FOUND then null;end;SQL Queries and Programs Examples Part - 2  Run these sample programs and check out the output.Programs declare            a number;begin            select sal into a FROM emp where empno = 7839;            dbms_output.put_line(a);EXCEPTION            when others then                        dbms_output.put_line(sqlerrm(sqlcode));end;---------------------------------------------------------------------------------------------------------------------------declare

Page 86: Complete SQL Commands

            a emp%ROWTYPE;begin            select * into a FROM emp where empno = 7839;            dbms_output.put_line(a.empno||' '||a.ename||' '||a.sal);EXCEPTION            when others then                        dbms_output.put_line(sqlerrm(sqlcode));end;---------------------------------------------------------------------------------------------------------------------------declare            my_grade salgrade.grade%type;            my_losal salgrade.losal%type;            my_hisal salgrade.hisal%type;begin            select grade, losal, hisal into my_grade,my_losal,my_hisal FROM salgrade where grade = 3;            dbms_output.put_line(my_grade||' '||my_losal||' '||my_hisal);EXCEPTION            when others then                        dbms_output.put_line(sqlerrm(sqlcode));end;---------------------------------------------------------------------------------------------------------------------------declare            x number:=20;            y number:=10;begin            declare                        x number:=5;                        z number:=99;            begin                        dbms_output.put_line('x='||x||' '||'y='||y||' '||'z='||z);            end;            dbms_output.put_line('x='||x||' '||'y='||y);end;---------------------------------------------------------------------------------------------------------------------------<<outer>>declare            x number:=20;begin            <<inner>>            declare                        x number:=5;            begin                        <<deep>>                        declare                                    x number:=7;                        begin                                    dbms_output.put_line('x='||x||' '||'Outer x='||outer.x||' '||'Inner x='||Inner.x);                        end;            end;end;---------------------------------------------------------------------------------------------------------------------------declare            a number;begin            select sal into a FROM emp where empno = 7777;            dbms_output.put_line(a);EXCEPTION            when NO_DATA_FOUND THEN                        dbms_output.put_line('Caught NDF exception');            when others then

Page 87: Complete SQL Commands

                        dbms_output.put_line(sqlerrm(sqlcode));end;

 declare            name varchar2(30):='&Name';            ct number := 1;begin            loop                        exit when ct = 10;                        dbms_output.put_line(ct||' '||name);                        ct := ct + 1;            end loop;            dbms_output.put_line('Alias out of the loop!!');end;---------------------------------------------------------------------------------------------------------------------------declare            name varchar2(30):='&Name';            ct number := 1;begin            while ct <> 10            loop                        dbms_output.put_line(ct||' '||name);                        ct := ct + 1;            end loop;            dbms_output.put_line('Alias out of the loop!!');end;---------------------------------------------------------------------------------------------------------------------------declare            name varchar2(30):='&Name';begin            for ct in 1..10            loop                        dbms_output.put_line(ct||' '||name);            end loop;            dbms_output.put_line('Alias out of the loop!!');end;---------------------------------------------------------------------------------------------------------------------------declare            name varchar2(30):='&Name';begin            for ct in reverse 1..9            loop                        dbms_output.put_line(ct||' '||name);            end loop;            dbms_output.put_line('Alias out of the loop!!');end;---------------------------------------------------------------------------------------------------------------------------declare            name varchar2(30):='&Name';begin            for ct in reverse 1..9            loop                        dbms_output.put_line(ct||' '||name);                        return; --Is equivalent of "exit" in C.            end loop;            dbms_output.put_line('Alias out of the loop!!');end;

Page 88: Complete SQL Commands

---------------------------------------------------------------------------------------------------------------------------begin            for i in 1..5            loop                        for j in 1..5                        loop                                    for k in 1..5                                    loop                                                exit when k = 3;                                                dbms_output.put_line(i||' '||j||' '||k);                                    end loop;                        end loop;            end loop;end;

 begin            <<outer>>            for i in 1..5            loop                        for j in 1..5                        loop                                    for k in 1..5                                    loop                                                exit outer when k = 3;                                                dbms_output.put_line(i||' '||j||' '||k);                                    end loop;                        end loop;            end loop;end;---------------------------------------------------------------------------------------------------------------------------begin            for i in 1..5            loop                        for j in 1..5                        loop                                    dbms_output.put(j*i||'   ');                        end loop;            dbms_output.put_line(' ');            end loop;end;---------------------------------------------------------------------------------------------------------------------------begin            for i in (select * from emp)            loop                        dbms_output.put_line(i.empno||' '||i.ename||' '||i.job);            end loop;end;declare            gender varchar2(1) := '&Gender';begin            if gender = 'F' then                        dbms_output.put_line('Hello Mam.');            elsif gender = 'M' then                        dbms_output.put_line('Hello Sir.');        else                        dbms_output.put_line('Invalid Option.');            end if;end;

Page 89: Complete SQL Commands

---------------------------------------------------------------------------------------------------------------------------declare            a number := 10;            b number := 20;            c number:=30;begin            if a > b then                        if a > c then                                    dbms_output.put_line(a||' is greatest.');                        else                                    dbms_output.put_line(c||' is greatest.');                        end if;            else                        if b > c then                                    dbms_output.put_line(b||' is greatest.');                        else                                    dbms_output.put_line(c||' is greatest.');                        end if;            end if;end;---------------------------------------------------------------------------------------------------------------------------declare            below_cr_lt EXCEPTION;            my_sal number;begin            select sal into my_sal from emp            where empno = 7839;             if my_sal < 6000 then                        raise below_cr_lt;        end if;exception            when below_cr_lt then                        dbms_output.put_line('Sorry!!!');            when others then                        dbms_output.put_line(sqlerrm(sqlcode));end;

 Select length(ename) -length(translate(ename,'1aeiouAEIOU','1')), ename from emp---------------------------------------------------------------------------------------------------------------------------declare            gn number(3) := &Number_Please;            lt number(2) := gn / 2;            ct number(2) := 3;begin            if gn = 2 or gn = 3 then                        goto prime;            elsif mod(gn,2) = 0 then                        goto noprime;            else                        while (ct <= lt)                        loop                                    if mod(gn,ct) = 0 then                                                goto noprime;                                    end if;                                    ct := ct + 2;                        end loop;                        goto prime;

Page 90: Complete SQL Commands

            end if;            <<noprime>>            dbms_output.put_line(gn||' is not prime.');            goto pend;            <<prime>>            dbms_output.put_line(gn||' is prime.');            <<pend>>            null;end;---------------------------------------------------------------------------------------------------------------------------declare            cursor c1 is select * from dept;            drec dept%rowtype;begin            open c1;            loop                        fetch c1 into drec;                        exit when c1%NOTFOUND;                        dbms_output.put_line(drec.dname||' '||drec.loc||' '||drec.deptno);            end loop;            close c1;end;---------------------------------------------------------------------------------------------------------------------------declare            cursor c1 is select * from dept;            drec dept%rowtype;begin            open c1;            loop                        fetch c1 into drec;                        exit when c1%NOTFOUND;                        dbms_output.put_line(drec.dname||' '||drec.loc||' '||drec.deptno);            end loop;            close c1;            dbms_output.put_line('===============================');            FOR I IN C1            LOOP                        dbms_output.put_line(I.dname||' '||I.loc||' '||I.deptno);            END LOOP;end;---------------------------------------------------------------------------------------------------------------------------DECLARE            CURSOR C1(D NUMBER) IS SELECT * FROM EMP WHERE DEPTNO = D;            CURSOR C2 IS SELECT * FROM DEPT;BEGIN            FOR I IN C2             LOOP                        DBMS_OUTPUT.PUT_LINE('=============================');                        DBMS_OUTPUT.PUT_LINE(I.DEPTNO||'    '||I.DNAME||'   '||I.LOC);                         DBMS_OUTPUT.PUT_LINE('=============================');                         FOR J IN C1(I.DEPTNO)                         LOOP                                    DBMS_OUTPUT.PUT_LINE(J.ENAME||'   '||J.JOB||'    '||J.SAL);                         END LOOP;             END LOOP;END;SQL Queries and Programs Examples Part - 3  Run these sample programs and check out the output.  

Page 91: Complete SQL Commands

declare            tn varchar2(30) := '&Table_Name';            cn varchar2(30) := '&Column_Name';            type refCursorType is ref cursor;            rcv refCursorType;            str varchar2(30);            val varchar2(30);begin            dbms_output.put_line(cn);            str := 'Select '||cn||' from '||tn;            open rcv for str;            loop                        fetch rcv into val;                        exit when rcv%notfound;                        dbms_output.put_line(val);            end loop;            close rcv;end;---------------------------------------------------------------------------------------------------------------------------declare            n ff.a%type;begin            insert into ff(a) values(98);            commit;            select a into n from ff     where a = 98;            dbms_output.put_line(n);EXCEPTION            when DUP_VAL_ON_INDEX then                        dbms_output.put_line('Insertion failed as such a value already exists.');            when NO_DATA_FOUND then                        dbms_output.put_line('No such number.');            when others then                        dbms_output.put_line(sqlerrm(sqlcode));end;---------------------------------------------------------------------------------------------------------------------------declare            cursor c1 is select * from dept;            drec dept%rowtype;begin            open c1;            open c1;loop            fetch c1 into drec;            exit when c1%notfound;            dbms_output.put_line(drec.dname||' '||drec.loc||' '||drec.deptno);end loop;close c1;exception            when CURSOR_ALREADY_OPEN then                        dbms_output.put_line('Forgot!! You have an open cursor.');            when INVALID_CURSOR then                        dbms_output.put_line('Hey!!! You have not opened the cursor.');            when others then                        dbms_output.put_line(sqlerrm(sqlcode));end;---------------------------------------------------------------------------------------------------------------------------declare            cursor c1 is select * from dept;            drec dept%rowtype;begin

Page 92: Complete SQL Commands

            open c1;                        if c1%ISOPEN then                                    dbms_output.put_line('Cursor is open.');                        else                                    dbms_output.put_line('Cursor has to be opened.');                        end if;                        loop                                    fetch c1 into drec;                                    exit when c1%rowcount = 3;                                    dbms_output.put_line(drec.dname||' '||drec.deptno);                        end loop;            close c1;end;

 declare            min_bal constant number := 500;            over_drawn exception;            withdrawl_amt number := 1000;            mybal number;begin            select bal into mybal from acct where no = 2;            if mybal - withdrawl_amt < 500 then                        raise over_drawn;            else                        update acct set bal = bal - withdrawl_amt where no = 2;                        commit;            end if;exception            when over_drawn then                        dbms_output.put_line('Sorry!! sir/madam minimum balance is Rs.500/-.');            when others then                        dbms_output.put_line(sqlerrm(sqlcode));end;---------------------------------------------------------------------------------------------------------------------------begin            lock table acct in exclusive mode nowait;exception            when others then                        dbms_output.put_line(sqlerrm(sqlcode));end;declare            table_locked exception;            pragma exception_init(table_locked, -00054);begin            lock table acct in exclusive mode nowait;exception            when table_locked then                        dbms_output.put_line('The table is locked. Please try after some time.');            when others then                        dbms_output.put_line(sqlerrm(sqlcode));end;---------------------------------------------------------------------------------------------------------------------------declare            cursor c1 is select * from ratio for update;            rrec ratio%rowtype;begin            open c1;            loop

Page 93: Complete SQL Commands

            fetch c1 into rrec;            exit when c1%notfound;            begin                        update ratio set r = rrec.a / rrec.b where current of c1;                        commit;                        exception                        when ZERO_DIVIDE then                        update ratio set r = 0 where current of c1;                        commit;            end;            end loop;            close c1;end;---------------------------------------------------------------------------------------------------------------------------declare            no_data_found exception;            n number;begin            select sal into n from emp where empno = 7777;            dbms_output.put_line('Employee no 7777 is drawing'||n);exception            when standard.no_data_found or no_data_found then                        dbms_output.put_line('Caught no data found');            when others then                        dbms_output.put_line('Caught others exception');            dbms_output.put_line(sqlerrm(sqlcode));end;

 create or replace procedure Playwin(no in number, prize out number) asbegin            dbms_output.put_line('Your ticket Number is '||no);            dbms_output.put_line('You have got a prize!! Keep Playing...');            prize := ((no / 3) * 24 )+ 4 ;end;declare            tno number: 123456;            prize number;begin            playwin(tno, prize);            dbms_output.put_line('You have become '||prize||' pati.');end;---------------------------------------------------------------------------------------------------------------------------create or replace function CompInt(pri in number, noy in number,  roi in number)return numberis            ci number;begin            ci := pri * power((1 + roi/100),noy);            return ci;end;---------------------------------------------------------------------------------------------------------------------------declarec number;beginc := CompInt(100,1,10);dbms_output.put_line('The compound interest = '||c);end;---------------------------------------------------------------------------------------------------------------------------

Page 94: Complete SQL Commands

create or replace procedure CalTot(up number, qty number, runtot in out number)asbegin            runtot := runtot + (up * qty);end;declare            total number := 0;            HamamQ number := 7;            HamamP number := 10;            BaboolQ  number := 3;            BaboolP number := 16;        HuggyQ number  := 1;            HuggyP number := 80;begin            CalTot(HamamP, HamamQ, Total);            dbms_output.put_line('Total so far (Hamam) '||Total);            CalTot(BaboolP, BaboolQ, Total);            dbms_output.put_line('Total so far (Hamam,Babool) '||Total);            CalTot(HuggyP, HuggyQ, Total);            dbms_output.put_line('Total so far (Grand) '||Total);end;---------------------------------------------------------------------------------------------------------------------------create or replace procedure Greet(n number default 5)isbegin            for i in 1..n            loop                        dbms_output.put_line('Greetings!!!');            end loop;end;---------------------------------------------------------------------------------------------------------------------------begin            Greet(7);end;CREATE OR REPLACE PACKAGE BODY emp_actions AS  -- bodyCURSOR desc_salary RETURN EmpRecTyp ISSELECT empno, sal FROM emp ORDER BY sal DESC;PROCEDURE hire_employee ( ename  VARCHAR2,  job VARCHAR2, mgr NUMBER, sal NUMBER, comm   NUMBER, deptno NUMBER) ISBEGIN            INSERT INTO emp VALUES (empno_seq.NEXTVAL, ename, job, mgr, SYSDATE, sal, comm, deptno);END hire_employee;PROCEDURE fire_employee (emp_id NUMBER) ISBEGIN            DELETE FROM emp WHERE empno = emp_id;END fire_employee;END emp_actions;

 CREATE OR REPLACE PACKAGE BODY emp_actions AS  -- bodyCURSOR desc_salary RETURN EmpRecTyp ISSELECT empno, sal FROM emp ORDER BY sal DESC;PROCEDURE hire_employee ( ename  VARCHAR2, job VARCHAR2, mgr NUMBER, sal NUMBER, comm   NUMBER, deptno NUMBER) ISBEGIN            INSERT INTO emp VALUES (empno_seq.NEXTVAL, ename, job, mgr, SYSDATE, sal, comm, deptno);END hire_employee;PROCEDURE fire_employee (emp_id NUMBER) ISBEGIN            DELETE FROM emp WHERE empno = emp_id;END fire_employee;

Page 95: Complete SQL Commands

END emp_actions;--------------------------------------------------------------------------------------------------------------------------- declarebegin            emp_actions.hire_employee('Akash','Analyst',7839,4999,null,10);            emp_actions.fire_employee(5);end;create or replace package body ox asfunction add( a number, b number ) return numberisbegin            return (a + b);end;function add(a varchar2, b varchar2) return varchar2isbegin            return a||b;end;function add(a varchar2, b number) return varchar2isbegin            return a||b;end;function add(a number, b varchar2) return varchar2isbegin            return a||b;end;end ox;---------------------------------------------------------------------------------------------------------------------------create or replace package ox asfunction add(a number, b number) return number;function add(a varchar2, b varchar2) return varchar2;function add(a number, b varchar2) return varchar2;function add(a varchar2, b number) return varchar2;end;---------------------------------------------------------------------------------------------------------------------------declare            A NUMBER := 12345;            B NUMBER := 56789;            C VARCHAR2(30) := 'RAM ';            D VARCHAR2(30) := ' LAKSHMAN';            RES VARCHAR2(20);            RESN NUMBER;BEGIN            RESN := OX.ADD(A,B);            DBMS_OUTPUT.PUT_LINE(RESN);            RES := OX.ADD(A,C);            DBMS_OUTPUT.PUT_LINE(RES);            RES := OX.ADD(D,A);            DBMS_OUTPUT.PUT_LINE(RES);            RES := OX.ADD(C, D);            DBMS_OUTPUT.PUT_LINE(RES);END;SQL Queries and Programs Examples Part - 4  Run these sample programs and check out the output. DECLAREBEGIN

Page 96: Complete SQL Commands

BT.CREATE_ACCT('AHMED',5000039);FOR I IN (SELECT * FROM ACCT)LOOP            DBMS_OUTPUT.PUT_LINE(I.ACCTNO||' '||I.NAME||' '||I.BAL);END LOOP;BT.DEPOSIT(1, 50000);FOR I IN (SELECT * FROM ACCT)LOOP            DBMS_OUTPUT.PUT_LINE(I.ACCTNO||' '||I.NAME||' '||I.BAL);END LOOP;BT.WITHDRAWL(1, 25000);FOR I IN (SELECT * FROM ACCT)LOOP            DBMS_OUTPUT.PUT_LINE(I.ACCTNO||' '||I.NAME||' '||I.BAL);END LOOP;END;---------------------------------------------------------------------------------------------------------------------------SQL>  CREATE TABLE ABC(A NUMBER , B DATE); Table created. SQL> CREATE TRIGGER 2 SQL> EDWrote file afiedt.buf 1 CREATE OR REPLACE TRIGGER ABC_TR2 BEFORE INSERT ON ABC3 FOR EACH ROW4 BEGIN5 DBMS_OUTPUT.PUT_LINE('A REC IS BEING INSERTED.');6 * END;7 / Trigger created. SQL> SET SERVEROUT ONSQL> INSERT INTO ABC(A,B) VALUES (1, SYSDATE);A REC IS BEING INSERTED. 1 row created. SQL> EDWrote file afiedt.buf 1 CREATE OR REPLACE TRIGGER ABC_DEL_TR2 AFTER DELETE ON ABC3 BEGIN4 DBMS_OUTPUT.PUT_LINE('TABLE IS BEING DELETED.');5 * END; SQL> / Trigger created. SQL> DELETE ABC; TABLE IS BEING DELETED.

Page 97: Complete SQL Commands

 1 row deleted. SQL> INSERT INTO ABC2 VALUES3

 SQL> ED Wrote file afiedt.buf 1 INSERT INTO ABC2 SELECT EMPNO, HIREDATE * FROM EMP SQL> /A REC IS BEING INSERTED.A REC IS BEING INSERTED.A REC IS BEING INSERTED.A REC IS BEING INSERTED.A REC IS BEING INSERTED.A REC IS BEING INSERTED.A REC IS BEING INSERTED.A REC IS BEING INSERTED.A REC IS BEING INSERTED.A REC IS BEING INSERTED.A REC IS BEING INSERTED.A REC IS BEING INSERTED.A REC IS BEING INSERTED.A REC IS BEING INSERTED. 14 rows created. SQL> COMMIT; Commit complete. SQL> DELETE ABC; TABLE IS BEING DELETED. 14 rows deleted. SQL> ROLL Rollback complete. SQL> SELECT * FROM ABC; A                     B-------              ---------7369                17-DEC-807499                20-FEB-817521                22-FEB-817566                02-APR-817654                28-SEP-817698                01-MAY-817782                09-JUN-817788                09-DEC-827839                17-NOV-817844                08-SEP-81

Page 98: Complete SQL Commands

7876                12-JAN-83 A                     B----------         --------7900                03-DEC-817902                03-DEC-817934                23-JAN-82 4 rows selected. SQL> CREATE TABLE ABC_BAK2 AS3 SELECT * FROM ABC WHERE 0=9; Table created.---------------------------------------------------------------------------------------------------------------------------select * from emp  

 Table Type Example. declare            type ty_tab is table of number;            v_tab ty_tab := ty_tab();begin            for i in 1..50                 loop                        v_tab.extend;                        v_tab(i) := (i);            end loop;            v_tab.delete(5); v_tab.delete(10); v_tab.delete(15);            for i in v_tab.first..v_tab.last            loop                        if v_tab.exists(i) then                                    dbms_output.put_line(i||' '||v_tab(i));                        else                                    dbms_output.put_line(i||' has been deleted.');                        end if;            end loop;end;/ Create Synonym Example CREATE PUBLIC SYNONYM AR_CUSTOMER_DETAILS FOR AR_CUSTOMER_DETAILS/ table 1:  mm_m_matgrp             create table mm_m_matgrp( mat_grp number(1) primary key, descr varchar2(70) not null, abvr varchar2(6), crt_by varchar2(10), crt_dt date, upd_by varchar2(10), upd_dt date); table2 : mm_m_matmain             create table mm_m_matmain( mat_grp number(1) constraint mt_grp_pk references mm_m_matgrp(mat_grp), mat_main number(2) primary key, descr varchar2(70) not null, abvr varchar2(6), crt_by varchar2(10), crt_dt date, upd_by varchar2(10), upd_dt date); table 3 : mm_m_matsub 

Page 99: Complete SQL Commands

            create table mm_m_matsub( mat_grp number(1) constraint mt_grp_fk references mm_m_matgrp(mat_grp), mat_main number(2) constraint mt_main_fk references mm_m_matmain(mat_main), mat_sub number(2) primary key, descr varchar2(70) not null, abvr varchar2(6), crt_by varchar2(10), crt_dt date, upd_by varchar2(10), upd_dt date); table 4 : mm_m_mat             create table mm_m_mat( mat_grp number(1) not null, mat_main number(2) not null, mat_sub number(2) not null, mat_sub2 number(2) not null, mat_cd number(7) primary key, descr varchar2(70) not null, abvr varchar2(6), uon varchar2 (10) not null, silo_stk_ind number(1), moist_ind number(1),no_wb_ind number(1), crt_by varchar2(10), crt_dt date, upd_by varchar2(10), upd_dt date); alter table mm_m_matgrp  

  create or replace trigger chk_view instead of insert onj_view for each rowbegininsert into dept (deptno,dname,loc) values(:new.deptno,:new.dname,:new.loc);insert into emp(empno,ename,job,sal,deptno) values(:new.empno,:new.ename,:new.job,:new.sal,:new.deptno);end;/ insert into j_view (empno,ename,sal,job,dname,loc,deptno)values(1023,'sdg',987,'com','ewe','JAPan',78); GV declarecursor deptcur isselect deptno from dept;--emp cursorcursor empcur(v_deptno dept.deptno%type) isselect ename from emp where deptno = v_deptno;beginfor deptrec in deptcur loopdbms_output.put_line('depertment no ...'|| deptrec.deptno);for emprec in empcur(deptrec.deptno) loopdbms_output.put_line('emp name ..'|| emprec.ename);end loop;end loop;end; NESTED TABLE step1:creation of a type

create type btype1 as object(bno number, bname varchar2(20),author varchar2(20));

step2:creation of table of the above type

create type btype1 as object(bno number, bname varchar2(20),author varchar2(20));

step3:creation of parent table

create type btype1 as object(bno number, bname varchar2(20),author varchar2(20));

step4:inserting the data

Page 100: Complete SQL Commands

create type btype1 as object(bno number, bname varchar2(20),author varchar2(20));

create type btype1 as object(bno number, bname varchar2(20),author varchar2(20));

step5:selecting

select s.bdetails from empbook s where empno=1002 PL SQL Table declare    type ty_tab is table of number index by binary_integer;    v_tab ty_tab ;begin    for i in 1..10        loop        v_tab(i*4) := (i);    end loop;    dbms_output.put_line(v_tab.count);    v_tab.delete(5); v_tab.delete(10); v_tab.delete(15);    for i in v_tab.first..v_tab.last    loop        if v_tab.exists(i) then            dbms_output.put_line(i||' '||v_tab(i));        end if;    end loop;end;/SQL Queries and Programs Examples Part - 5  Run these sample queries and check out the output.  SQL Query Syntaxselect col...from tablename[where conditiongroup by col...having condiitonorder by col.../ 1.SQL> select rtrim('xyxyxyxyxybosexxxxxxxxyxyxyx','xy') from dual;

RTRIM('XYXYXYX--------------xyxyxyxyxybose

2.SQL> select round(15.59,-1) from dual;

ROUND(15.59,-1)---------------             20

3.SQL> select trunc(15.59,-1) from dual;

TRUNC(15.59,-1)---------------             10 

Page 101: Complete SQL Commands

4.SQL> select nls_initcap('i jsland','nls_sort=xdutch') from dual;

NLS_INIT--------I Jsland

SQL> select nls_initcap('i jsland') from dual;

NLS_INIT--------I Jsland 5.SQL> select replace('jack and jue','j','bl') from dual;

REPLACE('JACKA--------------black and blue

SQL> select translate ('2krw229','0123456789abcdefghijklmnopqrstuvwxyz', '9999999999xxxxxxxxxxxxxxxxxxxxxxxxxx') from dual;

TRANSLA-------9xxx999 6. What is the difference between substr & substrb? 7. Instring? 8. SQL> SELECT NLS_INITCAP ('ijsland', 'NLS_SORT = XDutch') "Capitalized" FROM DUAL;

Capital-------IJslandSQL> SELECT NLS_INITCAP ('ijsland', 'NLS_SORT = Xfrench') "Capitalized" FROM DUAL;

Capital-------Ijsland 9. What is the difference between replace & translate? SQL & PL/SQL Interview Questions Part - 1 1. What is PL/SQL and what is it used for?             PL/SQL is Oracle's Procedural Language extension to SQL. PL/SQL's language syntax, structure and data types are similar to that of ADA. The PL/SQL language includes object oriented programming techniques such as encapsulation, function overloading, and information hiding (all but inheritance). PL/SQL is commonly used to write data-centric programs to manipulate data in an Oracle database. 2. Should one use PL/SQL or Java to code procedures and triggers?             Internally the Oracle database supports two procedural languages, namely PL/SQL and Java. This leads to questions like "Which of the two is the best?" and "Will Oracle ever de support PL/SQL in favor of Java?”                       Many Oracle applications are based on PL/SQL and it would be difficult of Oracle to ever desupport PL/SQL. In fact, all indications are that PL/SQL still has a bright future ahead of it. Many enhancements are still being made to PL/SQL. For example, Oracle 9iDB supports native compilation of Pl/SQL code to binaries.             PL/SQL and Java appeal to different people in different job roles. The following table briefly describes the difference between these two language environments:

Page 102: Complete SQL Commands

 PL/SQL: Data centric and tightly integrated into the databaseProprietary to Oracle and difficult to port to other database systemsData manipulation is slightly faster in PL/SQL than in JavaEasier to use than Java (depending on your background) JAVA: Open standard, not proprietary to OracleIncurs some data conversion overhead between the Database and Java type systemsJava is more difficult to use (depending on your background)  3. How can one see if somebody modified any code?            Code for stored procedures, functions and packages is stored in the Oracle Data Dictionary. One can detect code changes by looking at the LAST_DDL_TIME column in the USER_OBJECTS dictionary view. Example:             SELECT OBJECT_NAME, TO_CHAR(CREATED, 'DD-Mon-RR HH24:MI') CREATE_TIME, TO_CHAR(LAST_DDL_TIME, 'DD-Mon-RR HH24:MI’)             MOD_TIME, STATUS FROM USER_OBJECTS WHERE LAST_DDL_TIME > '&CHECK_FROM_DATE'; 4. How can one search PL/SQL code for a string/ key value?             The following query is handy if you want to know where a certain table, field or expressionis referenced in your PL/SQL source code. SELECT TYPE, NAME, LINE FROM   USER_SOURCE WHERE UPPER(TEXT) LIKE '%&KEYWORD%';

 5. How can one keep a history of PL/SQL code changes?             One can build a history of PL/SQL code changes by setting up an AFTER CREATE schema (or database) level trigger (available from Oracle 8.1.7). This way one can easily revert to previous code should someone make any catastrophic changes? Look at this example:CREATE TABLE SOURCE_HIST  -- Create history tableAS SELECT SYSDATE CHANGE_DATE, USER_SOURCE.* FROM   USER_SOURCE WHERE 1=2; CREATE OR REPLACE TRIGGER change_hist   -- Store code in hist tableAFTER CREATE ON SCOTT.SCHEMA              -- Change SCOTT to your schema nameDECLAREBEGIN            if DICTIONARY_OBJ_TYPE in ('PROCEDURE', 'FUNCTION', 'PACKAGE', 'PACKAGE BODY', 'TYPE') then  -- Store old code in SOURCE_HIST table                        INSERT INTO SOURCE_HIST                        SELECT sysdate, user_source.* FROM USER_SOURCE WHERE TYPE =  DICTIONARY_OBJ_TYPE AND NAME = DICTIONARY_OBJ_NAME;            end if;EXCEPTIONWHEN OTHERS THEN            raise_application_error(-20000, SQLERRM);END;/show errors 

Page 103: Complete SQL Commands

6. How can I protect my PL/SQL source code?             PL/SQL V2.2, available with Oracle7.2, implements a binary wrapper for PL/SQL programs to protect the source code. This is done via a standalone utility that transforms the PL/SQL source code into portable binary object code (somewhat larger than the original). This way you can distribute software without having to worry about exposing your proprietary algorithms and methods. SQL*Plus and SQL*DBA will still understand and know how to execute such scripts. Just be careful, there is no "decode" command available. The syntax is: wrap iname=myscript.sql oname=xxxx.plb 7. Can one print to the screen from PL/SQL?             One can use the DBMS_OUTPUT package to write information to an output buffer. This buffer can be displayed on the screen from SQL*Plus if you issue the SET SERVEROUTPUT ON; command. For example: set serveroutput onbegin            dbms_output.put_line('Look Ma, I can print from PL/SQL!!!');end;/             DBMS_OUTPUT is useful for debugging PL/SQL programs. However, if you print too much,the output buffer will overflow. In that case, set the buffer size to a larger value,eg: set serveroutput on size 200000             If you forget to set serveroutput on type SET SERVEROUTPUT ON once you remember,and then EXEC NULL;. If you haven't cleared the DBMS_OUTPUT buffer with the disable or enable procedure, SQL*Plus will display the entire contents of the buffer when it executes this dummy PL/SQL block. 8. Can one read/write files from PL/SQL?             Included in Oracle 7.3 is an UTL_FILE package that can read and write operating system files. The directory you intend writing to has to be in your INIT.ORA file (see UTL_FILE_DIR=... parameter). Before Oracle 7.3 the only means of writing a file was to use DBMS_OUTPUT with the SQL*Plus SPOOL command. Copy this example to get started: DECLARE            fileHandler UTL_FILE.FILE_TYPE;BEGIN            fileHandler := UTL_FILE.FOPEN('/tmp', 'myfile', 'w');            UTL_FILE.PUTF(fileHandler, 'Look ma, I''m writing to a file!!!\n');            UTL_FILE.FCLOSE(fileHandler);EXCEPTION            WHEN utl_file.invalid_path THEN                        raise_application_error(-20000, 'ERROR: Invalid path for file or path not in INIT.ORA.');END;/

9. Can one call DDL statements from PL/SQL?             One can call DDL statements like CREATE, DROP, TRUNCATE, etc. from PL/SQL by using the "EXECUTE IMMEDATE" statement. Users running Oracle versions below 8i can look at the DBMS_SQL package (see FAQ about Dynamic SQL). begin            EXECUTE IMMEDIATE 'CREATE TABLE X(A DATE)';end; 

Page 104: Complete SQL Commands

NOTE: The DDL statement in quotes should not be terminated with a semicolon. 10. Can one use dynamic SQL statements from PL/SQL?             Starting from Oracle8i one can use the "EXECUTE IMMEDIATE" statement to execute dynamic SQL and PL/SQL statements (statements created at run-time). Look at these examples.Note that  statements are NOT terminated by semicolons: EXECUTE IMMEDIATE 'CREATE TABLE x (a NUMBER)';-- Using bind variables...sql_stmt := 'INSERT INTO dept VALUES (:1, :2, :3)';EXECUTE IMMEDIATE sql_stmt USING dept_id, dept_name, location;-- Returning a cursor...sql_stmt := 'SELECT * FROM emp WHERE empno = :id';EXECUTE IMMEDIATE sql_stmt INTO emp_rec USING emp_id;             One can also use the older DBMS_SQL package (V2.1 and above) to execute dynamic statements.Look at these examples: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;/ More complex DBMS_SQL example using bind variables:            CREATE OR REPLACE PROCEDURE DEPARTMENTS(NO IN DEPT.DEPTNO%TYPE) ASv_cursor integer;v_dname  char(20);v_rows   integer;BEGINv_cursor := DBMS_SQL.OPEN_CURSOR;DBMS_SQL.PARSE(v_cursor, 'select dname from dept where deptno> :x', DBMS_SQL.V7);DBMS_SQL.BIND_VARIABLE(v_cursor, ':x', no);DBMS_SQL.DEFINE_COLUMN_CHAR(v_cursor, 1, v_dname, 20);v_rows := DBMS_SQL.EXECUTE(v_cursor);loopif DBMS_SQL.FETCH_ROWS(v_cursor) = 0 then            exit;end if;DBMS_SQL.COLUMN_VALUE_CHAR(v_cursor, 1, v_dname);DBMS_OUTPUT.PUT_LINE('Deptartment name: '||v_dname);end loop;DBMS_SQL.CLOSE_CURSOR(v_cursor);EXCEPTION when others thenDBMS_SQL.CLOSE_CURSOR(v_cursor);raise_application_error(-20000, 'Unknown Exception Raised: '||sqlcode||' '||sqlerrm);END;/SQL & PL/SQL Interview Questions Part - 2 11. What is the difference between %TYPE and %ROWTYPE?             The %TYPE and %ROWTYPE constructs provide data independence, reduces maintenance costs, and allows programs to adapt as the database changes to meet new business needs.%ROWTYPE is used to declare a record with the same types as found in the specified database table, view or cursor.Example: DECLARE

Page 105: Complete SQL Commands

            v_EmpRecord  emp%ROWTYPE;%TYPE is used to declare a field with the same type as that of a specified table's column. Example: DECLARE            v_EmpNo  emp.empno%TYPE; 12. What is the result of comparing NULL with NULL?             NULL is neither equal to NULL, nor it is not equal to NULL. Any comparison to NULL is evaluated to NULL. Look at this code example to convince yourself.declare            a number := NULL;            b number := NULL;begin            if a=b then                        dbms_output.put_line('True, NULL = NULL');            elsif a<>b then                        dbms_output.put_line('False, NULL <> NULL');            else                        dbms_output.put_line('Undefined NULL is neither = nor <> to NULL');            end if;end; 13. How does one get the value of a sequence into a PL/SQL variable?             As you might know, one cannot use sequences directly from PL/SQL. Oracle (for some silly reason) prohibits this:i := sq_sequence.NEXTVAL; However, one can use embedded SQL statements to obtain sequence values: select sq_sequence.NEXTVAL into :i from dual; Thanks to Ronald van Woensel 14. Can one execute an operating system command from PL/SQL?             There is no direct way to execute operating system commands from PL/SQL in Oracle7. However, one can write an external program (using one of the precompiler languages, OCI or Perl with Oracle access modules) to act as a listener on a database pipe (SYS.DBMS_PIPE). Your PL/SQL program then put requests to run commands in the pipe, the listener picks it up and run the requests. Results are passed back on a different database pipe. For an Pro*C example, see chapter 8 of the Oracle Application Developers Guide.             In Oracle8 one can call external 3GL code in a dynamically linked library (DLL or shared object). One just write a library in C/ C++ to do whatever is required. Defining this C/C++ function to PL/SQL makes it executable. Look at this External Procedure example.

 15. How does one loop through tables in PL/SQL? Look at the following nested loop code example.DECLARE            CURSOR dept_cur IS             SELECT deptno FROM dept ORDER BY deptno;            -- Employee cursor all employees for a dept number            CURSOR emp_cur (v_dept_no DEPT.DEPTNO%TYPE) IS            SELECT ename FROM emp WHERE deptno = v_dept_no;BEGIN            FOR dept_rec IN dept_cur LOOP                        dbms_output.put_line('Employees in Department '||TO_CHAR(dept_rec.deptno));

Page 106: Complete SQL Commands

             FOR emp_rec in emp_cur(dept_rec.deptno) LOOP                        dbms_output.put_line('...Employee is '||emp_rec.ename);            END LOOP;            END LOOP;            END;            / 16. How often should one COMMIT in a PL/SQL loop? / What is the best commit strategy?             Contrary to popular believe, one should COMMIT less frequently within a PL/SQL loop to prevent ORA-1555 (Snapshot too old) errors. The higher the frequency of commit, the sooner the extents in the rollback segments will be cleared for new transactions, causing ORA-1555 errors.To fix this problem one can easily rewrite code like this: FOR records IN my_cursor LOOP...do some stuff...COMMIT;END LOOP; ... to ...FOR records IN my_cursor LOOP...do some stuff...i := i+1;IF mod(i, 10000) THEN    -- Commit every 10000 records            COMMIT;END IF;END LOOP;             If you still get ORA-1555 errors, contact your DBA to increase the rollback segments. NOTE: Although fetching across COMMITs work with Oracle, is not supported by the ANSI standard. 17. I can SELECT from SQL*Plus but not from PL/SQL. What is wrong?             PL/SQL respect object privileges given directly to the user, but does not observe privileges given through roles. The consequence is that a SQL statement can work in SQL*Plus, but will give an error in PL/SQL. Choose one of the following solutions: Grant direct access on the tables to your user. Do not use roles! GRANT select ON scott.emp TO my_user;   Define your procedures with invoker rights (Oracle 8i and higher); Move all the tables to one user/schema. 18. What is a mutating and constraining table?             "Mutating" means "changing". A mutating table is a table that is currently being modifiedby an update, delete, or insert statement. When a trigger tries to reference a table that is in state of flux (being changed), it is considered "mutating" and raises an error since Oracle should not return data that has not yet reached its final state. Another way this 

SQL & PL/SQL Interview Questions Part - 4DDL DDL is Data Definition Language statements. Some examples: 1) CREATE 

Page 107: Complete SQL Commands

            -To create objects in the database 2) ALTER           -Alters the structure of the database Ex:- Alter (column to be modify must be empty to reduce the size or to Change the datatype) 

1)      alter table emp modify(ename varchar2(40)); Add (to add new column or new constraints)        1) alter table emp add(address varchar2(20));       2) alter table emp add foreign key(dept number) reference dept(deptno) on delete cascade;  3) DROP               -Delete objects from the database Ex:            Alter table drop column             Alter tableset unused (last_name)             Alter table drop unused columns 4) TRUNCATE          -Remove all records from a table, including all spaces Allocated for the records are removed 5) OMMENT            -Add comments to the data dictionary Difference between Delete and truncate     

          Delete                                                                TruncateDML                                                - It is DDLIt will mark the records to delete        - WE CAN'T ROLLBACKWe can rollback                               - WE CAN'T APPLY CONDITIONSlatter we use that space                    - It will releases the space and we can   

                                           All this type of values are stored in user_unused_col_tab table QUERIES: 1) Copy the rows of emp to emp1, if both are structure remains the same?             Insert into emp1            select * from emp; 2) If structure is not same, only the four columns in emp1?             Insert into emp1            Select empno, ename, sal, deptno from emp;.

Page 108: Complete SQL Commands

 3) Copying the structure of emp to emp1 “As it is” Here data also copied? But here constraints will not be copyed?             Create table emp2 as select * from emp; 4) I want to copy the only structure of emp in emp1? Here no data will be copied?             Create table emp1 as select * from emp where 1=2;

 Distinct key word: 1) Select all unique departments of employers?             Select distinct deptno from emp; In Operator:             --- is to define a list of elements or values            --- all the elements need to be enclosed with in paranthesis 1) list the emp those who are either clerks are analysis?             Select * from emp where job in(‘clerk’,’analysis’); Between operator:             ---is used to spa city the range            ---between operator not only work with numbers and also can work date datatype 1)list the employees of 1981?             Select * from emp Where hiredate between ’01-jan-1981’ and ’31-dec-1981’; 2)display the empno, name, sal, annual sal of all the emp in the descending order of annual sal?             Select eno, ename, sal,sal*12 annusal from emp order by annusal desc; 3)list the employees whose exp is ranging from 15 to 25 years?             Select * from emp where (sysdate-hiredate)/365 between 15 and 25; 4) write a query to display emp details of those working on dept 30 as clerks with out commotion?             Select * from emp where deptno=30 and job=’clerk’ and commotion is null; 5) Display the analyst & manager to the annual sal more than 30,000 working under some manager with out commotion with experience less than 30 years and whose name should not be equal to ‘blenk’ and who empno not equal to 7788 in descending order of salary?             Select * from emp Where job in(‘analyst’,’mamager’) and Sal * 12 > 30,000 and mgr is not null and comm. Is null and (hiredate-sysdate)/365 < 30 and Name ! = ‘black’ and empno != 7788 Order by sal desc; Like operator:             --- is to match a pattern of characters            --- the delimiters used along with like operator are -,%. 1) all the 5 charactores names starting with S?

Page 109: Complete SQL Commands

             select * from emp where ename like ‘S----‘; 2) all 5 charactores ending with H?             select * from emp where ename like ‘----H’; 3) list the emp who joined in the month which is started with A?             Select * from emo where hiredate like ‘A%’; 4) Those who joined in 1980’es?             Select * from emp where hiredate like ‘%8_’; DML                                                                                                                                                                                                                                        1)  SELECT             - retrieve data from the a database 2) INSERT              -insert data into a table

3) UPDATE              -updates existing data within a table Ex: 1) Transfer the emp’s of research to accounting?             Update emp Set deptno = (select deptno from dept where dname = ‘account’) where deptno= (select deptno from dept where dname = ‘research’); 2) DELETE                -deletes all records from a table, the space for the records remain Ex:- 1) Delete salesman without commotion?             Delete from emp Where job = ‘salesman’ and comm. Is null;           2) CALL                -call a PL/SQL or Java subprogram 3) EXPLAINS PLAN              -explain access path to data 4) LOCK TABLE               -control concurrency 5) MUTATINGTABLE

Page 110: Complete SQL Commands

             - Mutating Table is a table that is currently being modified by a DML statement. For a Trigger, this is the table on which the table is defined.           3) TCL                                                                                                                      TCL is Data Control Language statements. 

1.      COMMIT             - save work done 

2.      SAVEPOINT                  -identify a point in a transaction to which you can later roll backEx: savepoint (id) or (name)     

3.      ROLLBACK                -restore database to original since the last COMMIT Ex: rollback [to savepoint ] 

4.      SET TRANSACTION             -Change transaction options like what rollback segment to use Save point Ex:    Commit (work); Rollback:                       - Oracle Issues implicit commit before and after any DDL statement. Even if your DDL statement does not execute then also it Issues commit statement           -If we issue commit all savepoints will be erased and all locks are released

DCL: 1) GRANT:                       --- Is used to issue the privileges to other valid users of data base            1) User level                        --is granted by the DBA.                            2) Object level                       --These can be granted by one user to another userEx:

1.      Give select, update permit ions to the user demo on emp?                       Grant select, update On emp To demo; 

2.      Grant all permitions to the user’s sys and system on salgrade table?                       Grant all On salgrade To sys,system;       2) REVOKE:                    ----To cancel the permitionsEx:      1) cancle the select permition from the user sys the object salgrade?

Page 111: Complete SQL Commands

                               Revoke select On salgrde From sys Note:    1) user_pri_objects             2) user_table_pri             3) user_col_pri         Select * from DICT where table_name like ‘userpri%’; Intigrity constants:                                                                                                                        null, not null, default, check, primary key, foreign key 

1.      primary key:  NOT NULL+ UNIQUE +INDEX+ REFERENCED TO ANOTHER TABLE COLUMN VALUES (FOREIGN KEY).                 --ONE TABLE CAN HAVE ONLY ONE PRIMARY KEY

              -- PRIMARY KEY’S WE CAN’T UPDATE

           2.      unique : it will not allow duplicate values and it accept null values can be defined at the

            column level and table level 

3.      check: it will check with column definition before accept. check constraint defines a            CONDITION that each row must satisfy references to the currval, nextval, level, rownum pseudo            columns calls to sysdate uid user, and userenv. check cons. can be defined at the column level            and table level 

1. foriegn key: foreign keys provide referential integrity rules wither within a table or b/w Tables            - give reference to the primary key column. 

5.      references- identifies the table and column in the parent table.    On delete cascade- deletes the dependent rows in the child table when a row in the parent table is deleted. On delete set null - converts dependent foriegn key values to null.       Cascade constraint- the cascade constraints clause drops all referential integrity constraints that refer to the primary and unique keys defined on the dropped columns             -the cascade constraints clause also drops all multicolumn constraints defined in the dropped columns.