Você está na página 1de 14

PL/SQL Practical http://www.scribd.

com/doc/20245091/PL-SQL-Practicals

1. I want to display 1 to 10 numbers using one select statement. Select level from dual CONNECT BY LEVEL<=10; LEVEL 1 2 3 4 5 6 7 8 9 10 10 rows selected. OR Select rownum from USER_OBJECTS where rownum <= 10 order by rownum ASC; ROWNUM ---------1 2 3 4 5 6 7 8 9 10 10 rows selected. How to delete duplicate rows from a specified table (only single table) howdo you know which join is need to be used. DELETE FROM emp a WHERE ROWID > (SELECT MIN (ROWID) FROM emp b WHEREA.empno=b.empno); Why should required for Indexed by table in pl/sql. For good performance Index is required. What is the diff between Static Queries and Dynamic queries give me someexamples. Static queries are the queries we normally use like SELECT * FROM EMPLOYEE.Where as dynamic queries can be built and executed dynamically. sp_executesqlsystem stored procedure is used to execute dynamic sql statements. E.g.: sp_executesql N'select * from employee' Dynamic sql queries will take more time to execute when compared to static queries. What is the basic function for master, msdb, tempdb databases?

Master, MSDB and TempDB these are the inbuilt Database which r provided bySQL SERVER. All have their own functionality & responsibility like. 1. Master: Master DB is responsible for storing all information at system level. 2. MSDB: it is Microsoft DB; it creates a Copy of whole Database in it. 3. TempDB: it stores all the log information of Server, it will initializeautomatically whenever Server will start, the max. Size allotted fro TempDB is 10MB. I have doubt that any one tell ref cursor comes in sql pl/sql? pls clarify? Ref cursor comes in PL/SQL. You can return a ref cursor in a function.A ref cursor is useful while returning more values.It will use in PL/SQL. Reusability of Cursor is nothing but "REF CURSOR. Theseare of 2 types.1.W eak Ref cursor 2. Strong ref Cursor. If I have a table T with 4 rows & 2 columns A & B. A has values 1,2,3,4. AndB has 10,20,30,40. Write an Update SQL query which can Swap the values of A & B for all records. (Do not use a subquery)? UPDATE T SET A = B, B=A; What is a REF CURSOR? Compare strong and week ref cursor types. For the strong ref cursor the returning columns with data type and length needto be known at compile time. For the weak ref cursor the structure does not need to be known at compile time. TYPE WEAK_REF_CURSOR IS REF CURSOR; TYPE STRONG-_ REF_CURSOR IS REF CURSOR RETURN TABLE_NAME%ROWTYPE; How one can easily select all even, odd, or nth rows from a table using SQLqueries? Odd number of records: Select * from emp where (rowid, 1) in (select rowid, mod (rownum, 2) from emp); Output:-135 Even number of records: Select * from emp where (rowid, 0) in (select rowid, mod (rownum, 2) from emp); Output:-246 For n th number, Example we r considering number n=10 SELECT * FROM emp a WHERE 10= (SELECT COUNT (rowid) FROM emp bWHERE a.rowid >= b.rowid); What is the difference between the query and corelated query? Select * from emp; --->> query Select * from emp where sal = (select max (sal) from emp); --> Here a sub query is also thereSelect * from emp outer where sal= (select avg (sal) from emp eWhere dept.e=dept.outer) --> corelated query Or Select * from emp; ----- is a query; And Co-related query is sub one of sub query (sub query means--whose returning valuesare filtering the condition of the main query) SELECT * FROM EMP E WHERE E.SAL> (SELECT AVG (SAL) FROM EMP FWHERE E.DEPTNO= F.DEPTNO); SO HERE WE R FINDING THE EMPLOYEE WHO HAS GETTING MORE THAN AVG (SAL) OF RESPECTING DEPTNO.AND CO RELATED SUB QUERY ALWAYS USE ALIAS NAME FOR TABLE, IT SIMILARLIKE JAIN (SELF JOIN)

Use of IN/ANY/ALL IN - used to select multiple rows based on any of the key providedSQL - select distinct employeeid from orders where orderid in (select orderid fromorder details where discount >= 10) ANY - used in case of relational queries to compare result with any of the key.SQL - select custID from orders where regionID != "E" and discount > any (selectdiscount from orders where regionID = "E" and discount > 3) ALL - used in case of relational queries to compare result with all of the keys. SQL - select custID from orders where regionID != "E" and discount > all (selectdiscount from orders where regionID = "E" and discount > 3 Or IN- It will return the value based on the parameter;E.g. select * from emp where salary in ('1000','3000'); ANY-It will compare with any value that has been returned by the parameter; Select * from emp where salary > any (select salary from emp where deptno=10) The salary will be compared with any value that has been returned by the subquery. ALL-It will compare with max/min value that has been returned by the subquery; Select * from emp where salary > all (select salary from emp where deptno=10) The salary will be compared with the longest value that has been returned by the subquery. What are integrity constraints? Which prevents the user from entering the duplicating into tables or views iscalled integrity constraint.Ex: primary key constraint, foreign key constraint, unique constraint, checksconstraint.Integrity constraint is a rule that restricts a column of a table. Or Data integrity allows defining certain data quality requirements that the datain the database needs to meet. If a user tries to insert data that doesn't meet theserequirements, Oracle will not allow so. Constraint types There are five integrity constraints in Oracle. Not Null A column in a table can be specified not null. It's not possible to insert a nullin such a column. The default is null. So, in the following create table statement, anull can be inserted into the column named c. Create table ri_not_null (a number not null, b number null,c number); Insert into ri_not_null values ( 1, null, null); Insert into ri_not_null values ( 2, 3, 4); Insert into ri_not_null values (null, 5, 6); The first to records can be inserted; the third cannot, throw a ORA-01400:cannot insert NULL into ("RENE"."RI_NOT_NULL"."A"). The not null/null constraint can be altered with alter table ri_not_null modify a null; After this modification, the column a can contain null values.

Unique Key The unique constraint doesn't allow duplicate values in a column. If theunique constraint encompasses two or more columns, no two equal combinations areallowed. Create table ri_unique (a number unique,b number); However, if a column is not explicitely defined as not null, nulls can be insertedmultiple times: Insert into ri_unique values (4, 5); Insert into ri_unique values (2, 1); Insert into ri_unique values (9, 8); Insert into ri_unique values (6, 9); Insert into ri_unique values (null, 9); Insert into ri_unique values (null, 9); Now: trying to insert the number 2 again into a: Insert into ri_unique values (2, 7); This statement issues a ORA-00001: unique constraint (RENE.SYS_C001463violated). Every constraint, by the way, has a name. In this case, the name is:RENE.SYS_C001463. In order to remove that constraint, an alter table ... dropconstraint ... is needed: Alter table ri_unique drop constraint sys_c001463; Of course, it is also possible to add a unique constraint on an existing table: Alter table ri_unique add constraint uq_ri_b unique (b); A unique constraint can be extended over multiple columns: Create table ri_3 (a number, b number, c number, Unique (a,b) ); It is possible to name the constraint. The following example creates aunique constraint on the columns a and b and names the constraint uq_ri_3. Create table ri_3 (a number, b number, c number, Constraint uq_ri_3 unique (a,b) ); Primary Key On a technical level, a primary key combines a unique and a not nullconstraint. Additionally, a table can have at most one primary key. After creating aprimary key, it can be referenced by a foreign key. Create table ri_primary_key (a number primary key, b number); Primary keys can explicitly be named. The following create table statementcreates a table with a primary key whose name is pk_name.

Create table ri_primary_key_1 (a number, b number, c number, Constraint pk_name primary key (a, b) ); Foreign Key A foreign key constraint (also called referential integrity constraint) on a column ensures that the value in that column is found in the primary key of anothertable. If a table has a foreign key that references a table, that referenced table canbe dropped with a drop table... Cascade constraints. It is not possible to establish a foreign key on a global temporary table. If tried,Oracle issues a ORA-14455:Attempt to create referential integrity constraint on temporary table. Check A check constraint allows stating a minimum requirement for the value in acolumn. If more complicated requirements are desired, an insert trigger must be used. The following table allows only numbers that are between 0 and 100 in the column a; Create table ri_check_1 (a number check (a between 0 and 100), b number); Check constraints can be added after a table had been created: Alter table ri_check_1 Add constraint ch_b check (b > 50); It is also possible to state a check constraint that checks the value of morethan one column. The following example makes sure that the value of begin_ issmaller than the value of end_. Create table ri_check_2 (Begin_ number, End_ number, Value_ number, Check (begin_ < end_)); Select 1, col1, col2 from table1. Output? SQL> SELECT 1, emp_no, emp_name FROM emp; 1 EMP_NO EMP_NAME --------- --------- ------------------------1 100 SELVA 1 101 RAJ 1 102 A S KALA 1 103 JESLIN FANTA MALAR 1 104 ANITA1 105 MURUGU 1 106 SRIVATSAN1 107 SARABOOT 1 108 KARTHI SIR 1 109 SUDHA 1 110 MERCHI 1 111 SAVI

12 rows selected.

Does view contain data? No , View is a logical table associated with a query. It will not store any data in it. Only the query with which the view is created is stored in the database. NO, the view is a logical table based on one or more tables or views . Aview in practicality contains no data by itself. it contains only select statements . Which will fire first? Trigger or Constraint? Always constraint will fire first. If i perform any operation on views such as insert, delete etc will my basetable get affected????? Yes if it is simple view. Error if it is compute viewOrIt will affect ur base table only when u having a simple view and if you put nullin the field which is primary key of the base table then also the base table will not affected. And if you are using the compute view then u r not able to insert or deletethe records. How to retrieve only duplicate values in a table. For example have a table called student like below. STUD-NAME SUBJECT --------- -----STUD1 A STUD2 B STUD2 A STUD1 A In this structure 1 row is duplicated in 4th. So we can fetch the student nameusing the below query. SELECT stud-name FROM STUDENT GROUP BY stud-name, subjectHAVING COUNT > 1; OrSelect count (<Duplicate_FieldName>), fees from Table Name Group by <Duplcate_FieldName>Having count (<Duplicate_FieldName>)>1; Write the Sql query for creating database backup? If you need to take tha backup of the database on ur hard disk then u can use thefollowing query: Exp userid=system/manager@orcl file=location\abc.dmp full=yLog= abc What is TABLE SPACE? Database is logically divided into three tablespaces. Once creates the databasethen automatically create tablespace is also called SYSTEM tablepace.tablespacecontain data dictionary of all data.OrA Table space is a logical group of data files in a database. A typical data baseconsists at least one table space, and usually two or more. In a database a tablespace plays a role similar to that of a folder on the hard drive of a computer. What is SGA? System global a rea (SGA) is a shared memory region allocated by ORACLEthat contains data and control information for one ORACLE instance.

What is pseudo column?

A pseudo column is an item of data which does not belong in any particulartable but which can be treated as if it did. Any SELECT list of columns can includethese pseudo columns. SYSDATE current date and time ROWNUM sequence number assigned to retrieved rows ROWID unique identifier for a row UID number associated with a user USER userid of current user Or Pseudo column is a act as an database table column ,but its not a actualcolumn in a table , we can fetch value from a pseudo column. Ex. User, UserID RowID, RowNum Level CurrVal, NextVal Sysdate How to retrive only second row from table? SELECT * FROM emp a WHERE 2 = (SELECT COUNT (rowid) FROMemp b WHERE a.rowid >= b.rowid); Find the 2nd Highest Salary?? SELECT * FROM EMPLOYEES A WHERE 2=(SELECT COUNT(DISTINCT SALARY) FROMEMPLOYEES B WHERE B.SALARY>=A.SALARY); Delete duplicate records in the emp table. DELETE FROM EMP EWHERE E.ROWID <> (SELECT MIN (ROWID) FROM EMP E2 WHEREE.EMP_NO=E2.EMPNO); SELECT * FROM EE E1 WHERE E1.ROWID<>(SELECT MAX(ROWID) FROM EE E2WHERE E1.ENO=E2.ENO); Or Delete from emp where rowid not in (select min (rowid) fromemp group by empno; Delete the emps whose salaries are lowest sals of their own dept. Delete from emp where (depno, nvl2 (sal, sal, 0)) in(Select depno,min(nvl2(sal,sal,0)) from emp group by depno ); Define a variable representing the expression used to calculate on empstotal annual remuneration.use the variable in a statement which finds allemps who can earn 30000 a year or more. Select Empno,Annual_Salary=sum(Month_Salary) fromEmployee_SalaryGroup by Empno having sum (Month_Salary)>30000 Or Example: Declare Cursor cl is select empname,salary,(salary*12)annual Renumeration Begin

For i in cl Loop if i.annual renumeration > 30000 then dbmsoutput.putline(empname); End if End; Check whether all the emp numbers are indeed unique. Select empno from emp where empno is not null group by empnoHaving count (*) >1;

Can a table have two primary keys? Yes, a table may have more than 1 primary keys but, of them we onlychoose 1 column as identifiable column called primary key. The other columns are called surrogate keys or candidate key. Create table emp ( empno number(5), ename varchar2(20), deptno number(5)add primary key Pk_constraint( empno, deptno) );

What is purge command explain about oracle performance tuning Use the PURGE statement to remove a table or index from your recycle bina n d r e l e a s e all of the space associated with the object, or to remove the e n t i r e recycle bin, or to remove part of all of a dropped tablespace from the recycle bin. PURGE RECYCLEBIN; OrPurge command is used to clear the recycle bin.It can also be used with drop command. Ex. Drop table <tablename> purge; This command will clear away the table from database as well as from ther e c y c l e b i n . A f t e r f i r i n g o f p u r g e c o m m a n d y o u c a n n o t r e t r i v e t h e t a b l e u s i n g flashback query. What is the difference between RDBMS and DBMS 1) DBMS permits only one person to access the database at a given time.But RDBMSgives the multiple accesses the database at a given time. 2) DBMS organised the data in any formmate but RDBMS allows only in row andcolumn format. 3) In DBMS we can not create the the relationshs but in RDBMS we can not createthe relationship between the tables

Write a simple program on cursors Declare Cursor cur_t is select * from test; var_t test%rowtype; Begin Open cur_t; Loop Fetch cur_t into var_t; Exit when cur_t%notfound; dbms_output.put_line('a: ' || var_t.a || ', b: ' ||var_t.b);End loop; End; / Difference between views and materialized views? View: View is a virtual table,a query attached to it. Actually it has notstored query results. It will execute and returns rows.A materialized view is a database object that contains the results of aquery . They are local copies of data located remotely , o r a r e u s e d t o c r e a t e summary tables based on aggregations of a table's data. Materialized views, which store data based on remote tables are also, know as snapshots. A materialized view can query tables, views, and other materialized views. Collectively these are calledmaster tables (a replication term) or detail tables (a data warehouse term). I want to display the employees who have joined in last two months. (Itshould be executed randomly means If I execute the query in March itshould display Jan and Feb joined employees. Same query if i execute inFeb, 2007 it should display dec, 2006 and Jan 2007 joined employees. Select * from empWhere trunc(months_between(sysdate, hiredate))=2; OR Select * from af where months_between(sysdate,hiredate)<=2 OR Select * from emp where hiredate between add_months(trunc(sysdate,'Month'),-2)And trunk (sysdate,'Month')-1 This works for sure. 100 % How to retrieve Duplicate Rows only in a Table? Suppose if a Table Name is"Education". It consists of multiple columns. Then if we insert rows into thistable with duplicate records then how can we retrieve only duplicaterecords from that table? select * from emp a ,(select empno,count(*) from emp group by empno havingcount(*) > 1) b where a.empno = b.empno; Differentiate between %type and %rowtype attribute in Oracle PL/AQLprogramming? ROWTYPE is declared at the record level and the TYPE is declared for thecolumn level. (TABLE Level). %type and %rowtype provides data independence, reduces maintenancecost and allows programs to adapt as the database changes due to new businessrequirements. %rowtype is used to declare a record with the same types as found in thespecified database table, view or a cursor. %Rowtype is used to declare a record that represents a particular row of a table.

%type is used to declare a field with the same type as found in the specifiedtable's column. (COLUMN Level). %Type is used to change the size of any datatype but only for one record. SQL> select * from empn; EMP_ID FIRST_NAME LAST_NAME HIREDATE --------- ------------------------- ------------------------- --------- 101 SELVA RAJ 20-MAY-85 102 NANDHINI DEVI 15-APR7103 JESLIN SHANTHAMALAR 25-MAR-84104 MERCY JAYANTHI 26-MAY85105 SATHISH KUMAR 27-JAN-90110 A S KALA A S 12-SEP-03121 MALAR SANTHA 02-FEB01126 PADMA SHEELA 21-JAN-05 8 rows selected. SQL> declare 2 v_EMP_ID empn.EMP_ID%type; 3 v_FIRST_NAME empn.FIRST_NAME%type; 4 cursor empn_cursor is 5 select EMP_ID,FIRST_NAME from empn; 6 begin 7 open empn_cursor; 8 loop 9 fetch empn_cursor into v_EMP_ID,v_FIRST_NAME; 10 exit when empn_cursor%rowcount>7; 11 dbms_output.put_line(to_char(v_EMP_ID)||' '||v_FIRST_NAME); 12 end loop; 13 close empn_cursor; 14 end; 15 / 101 SELVA 102 NANDHINI 103 JESLIN 104 MERCY 105 SATHISH 110 A S KALA 121 MALAR What is a constraint? Types of constraints? Constraint is a restriction on table .There is two types of constraints, 1. Ananymous constraint and 2. named constraint. Under named and anonymous constraints there are 1. Primary key constraint 2. Foreign key constraint 3. Not null constraint 4. Check constraint 5. Unique constraint. 6. Default. What is user defined stored procedures? Stored procedures are basically set of sql statements . User definedstored procedures are

created by users in which they can use functions,procedures to get the desired result from database. What is an index and types of indexes? How many numbers of indexes canbe used per table? Indexes are used for the faster retrieval of data. Two types of indexes: Cluster index, unclustered index We can have one cluster index and upto 249 cluster indexes for a table What is normalization? Normalization is a rule applied on the database table in order to Remove redundancy of data. Normalization is the process of organizing the table to remove redundancy. Normalization is a process to remove data redundancyNormalization is the process of breaking of data and storing it into differenttables to reduce the redundency and to avoid nulls. 1NF Eliminate Repeating Groups - Make a separate table for each set of relatedattributes, and give each table a primary key. 2NF Eliminate Redundant Data - If an attribute depends on only part of a multi-valued key, remove it to a separate table. 3NF Eliminate Columns Not Dependent on Key - If attributes do not contribute toa description of the key removes them to a separate table. BCNF Boyce-Codd Normal Form - If there are non-trivial dependencies betweencandidate key attributes, separate them out into distinct tables. 4NF Isolate Independent Multiple Relationships - No table may contain two ormore 1:n or n:m relationships that are not directly related. 5NF Isolate Semantically Related Multiple Relationships - There may be practicalconstrains on information that justify separating logically related many-to-manyrelationships. ONF Optimal Normal Form - a model limited to only simple (elemental) facts, asexpressed in Object Role Model notation. DKNF Domain-Key Normal Form - a model free from all modification anomalies. What is INSTEAD OF trigger? Instead of trigger is used to update the database tables associated with the view instead of updating the view directly. How to retrieve the top 3 salaries of the table using rownum Select salary_column from salary_table where rownum<4 order by salary_column desc; Or Select e.ename,e.sal from emp e where 3>(select count (distinct(b.sal)) fromemp b where b.sal>e.sal); Or

Select empname,sal from (select empname,sal from dh1 order by sal desc)where rownum < =4 order by sal descOrSelect sal from emp a where 3> (select Count (distinct (sal)) from emp b wherea.sal<b.sal); What is the difference between union and union all? Union is used to select distinct values from two tables where as union all is used to select all values including Duplicates from the tables. Union will return only distinct values from two tables. Union all will returnduplicate values from the two tables. What is correlated sub-query? Select empno, ename from emp where deptno in(Select deptno from dept where dept.deptno=emp.deptno); When inner subquery has a reference to outer query then this is know asCorrelated sub-query. What is the usage of SAVEPOINTS? Save points are used to mark our transactions . Then later on, down the line,we can roll back to that particular Transaction and roll back can be issued to thatparticular point. Difference between SUBSTR and INSTR? SUBSTR is used to extract a set of characters from a string by specifying thecharacter starting position and end position and length of characters to be fetched. Example: substr('hello',2,3) will return ' el l' INSTR is used to find the position of any particular character in a word whichreturns numeric value. instr('hello','e') - will return the position of 'e' as 2 SELECT instr('hello','e') FROM dual; SELECT substr('hello',2,3) FROM dual;

What is ON DELETE CASCADE? The main use of ON DELETE CASCADE is to delete the child records automatically from a table when the related records from master table are deleted.Assign the ON DELETE CASCADE clause while creating the foreign key.

If a View on a single base table is manipulated will the changes be reflectedon the base table? Yes it will be reflected in the base table.Yes, definitely. Since the view is based on a single table and falls within thecategory of simple view. Any change / Modification on the records will be reflectedin the base table. What are CYCLE/NO CYCLE in a Sequence? NO CYCLE is default when sequence is created CYCLE statement is given when the sequence has to repeat

its numbergeneration between START WITH and MAX VALUE. How to access the current value and next value from a sequence? Select sequencename.currval from dualSelect sequencename.nextval from dual Explain Connect by Prior? Retrieves rows in hierarchical order. E.g.: select empno, ename from emp whereThe start with... connect by clause can be used to select Data that has ahierarchical relationship (usually some sort of parent->child (boss->employee orthing->parts). Select a.*, level from emp aStart with mgr is nullConnect by mgr = prior empno; What is an Integrity Constraint? Integrity Constraints is used by oracle to check data Integrity whileperforming operations into database. Like columns is defined as not null. User cannotinsert null Values into this column.Constraints: 1. Primary Key 2. Unique Key 3. Not Null 4. Referential Integrity (Foreign Key) 5. Check Constraints

Integrity Constraints prevent invalid data entry into the Table. Theseconstraints set a range and any violation takes Place oracle prevents the userfrom performing manipulation on the table. What are the data types allowed in a table? 1)Varchar2 () 2) Date3) TIMESTAMP [(precision)] default precision is 6 we can mention from 0...94) Long5) Integer6) Number7) Char8) clob9) Raw ()10) pls_integer11) binary_integer12) Nvarchar2 ()13) bfile How to perform a loop through all tables in pl/sql? We can use user_tables view of data dictionary. Create a cursor based on query Select * from user_tables and then use use this cursor in for loop How to find out second largest value in the table. SELECT * FROM PRODUCT A WHERE 2=(SELECT COUNT(DISTINCT B.ROWID)FROM PRODUCT B WHERE B.ROWID>=A.ROWID); PROD_I PROD_NAME PROD_PRICE -------- -------------- -------------MO123 MONITOR 25000 DUPLICATE? SELECT COUNT (*) FROM REGIST_093_MANUAL WHERE ROWID IN (SELECT MAX(ROWID) FROM REGIST_093_MANUAL GROUP BY REGNNUMB, SUBJUNCD, SUBJCODE, REGISTER HAVING COUNT (*)>1) AND REGNNUMB='90202107037';

AGE CALCULATION IN PL/SQL: DECLARE SD DATE; ED DATE DEFAULT SYSDATE; Y NUMBER; M NUMBER; D NUMBER; BEGINSD:='&SD'; Y:=trunc( months_between( ED, SD ) /12 ); M:=mod( trunc( months_between( ED, SD ) ), 12 ); D:=ED - add_months(SD,trunc( months_between( ED, SD ) )); DBMS_OUTPUT.PUT_LINE(Y || ' Years'||',' || M || ' Months' ||','|| D || ' Days'); END; OUTPUT :Enter value for sd: 11-AUG-1983 26 Years,1 Months,10.41363425925925925925925925925925925926 Days

Você também pode gostar