Saturday, December 27, 2008

Useful Oracle Queries

1) Display the name of employees along with their annual salary (sal*12) the name of the employee earning highest annual salary should appear first?
Select ename, sal, sal*12 "Annual Salary" from EMP order by "Annual Salary" desc;

2) Display name, salary, Hra, pf, da, TotalSalary for each employee. The out put should be in the order of total salary, hra 15% of salary, DA 10% of salary .pf 5% salary Total Salary will be (salary+hra+da)-pf?
Select ename, sal SA, sal*0.15 HRA, sal*0.10 DA, sal*5/100 PF, sal+ (sal*0.15) + (sal*0.10) -(sal*.05) TOTALSALARY from emp ORDER BY TOTALSALARY DESC;
3) Display Department numbers and total number of employees working in each Department?
Select deptno, count (*) from emp group by deptno;
4) Display the various jobs and total number of employees working in each job group?
Select job, count (*) from emp group by job;
5) Display department numbers and Total Salary for each Department?
Select deptno, sum (sal) from emp group by deptno;
6) Display department numbers and Maximum Salary from each Department?
Select deptno, max (Sal) from emp group by deptno;
7) Display various jobs and Total Salary for each job?
Select job, sum (sal) from emp group by job;
8)Display each job along with min of salary being paid in each job group?
Select job, min (sal) from emp group by job;
9) Display the department Number with more than three employees in each department?
Select deptno, count (*) from emp group by deptno having count (*)>3;
10) Display various jobs along with total salary for each of the job where total salary is greater than 40000?
Select job, sum (sal) from emp group by job having sum (Sal)>40000;
11) Display the various jobs along with total number of employees in each job. The output should contain only those jobs with more than three employees?
Select job, count (*) from emp group by job having count (*)>3;
12) Display the name of employees who earn Highest Salary?
select ename, sal from emp where sal>=(select max(sal) from emp );
13) Display the employee Number and name for employee working as clerk and earning highest salary among the clerks?
select ename,empno from emp where sal=(select max(sal) from emp where job='CLERK') and job='CLERK' ;
14) Display the names of salesman who earns a salary more than the Highest Salary of the Clerk?
select ename,sal from emp where sal>(select max(sal) from emp where job='CLERK') AND job='SALESMAN';
15) Display the names of clerks who earn a salary more than the lowest Salary of any Salesman?
select ename,sal from emp where sal>(select min(sal) from emp where job='SALESMAN') and job='CLERK';
16) Display the names of employees who earn a salary more than that of jones or that of salary greater than that of scott?
select ename,sal from emp where sal>all(select sal from emp where ename='JONES' OR ename='SCOTT');
17) Display the names of employees who earn Highest salary in their respective departments?
select ename,sal,deptno from emp where sal in (select max(sal) from emp group by deptno);
18) Display the names of employees who earn Highest salaries in their respective job Groups?
select ename,job from emp where sal in (select max(sal) from emp group by job);
19)Display employee names who are working in Accounting department?
select e.ename,d.dname from emp e,dept d where e.deptno=d.deptno and d.dname = 'ACCOUNTING';
20) Display the employee names who are Working in Chicago?
select e.ename,d.loc from emp e,dept d where e.deptno=d.deptno and d.loc='CHICAGO';
21) Display the job groups having Total Salary greater than the maximum salary for Managers?
select job ,sum(sal) from emp group by job having sum(sal) >(select max(sal) from emp where job='MANAGER');
22) Display the names of employees from department number 10 with salary greater than that of ANY employee working in other departments?
select ename,deptno from emp where sal>any(select min(sal) from emp where deptno!=10 group by deptno) and deptno=10 ;
23) Display the names of employees from department number 10 with salary greater than that of ALL employee working in other departments?
select ename,deptno from emp where sal>all(select max(sal) from emp where deptno!=10 group by deptno) and deptno=10 ;
24) Display the names of Employees in Upper Case?
select upper(ename) from emp;
25) Display the names of employees in Lower Case?
select Lower(ename) from emp;
26) Display the names of employees in Proper case?
select InitCap(ename)from emp;
27) Find the length of your name using Appropriate Function?
select lentgh('RAMA') from dual;
28) Display the length of all the employee names?
select length(ename) from emp;
29) Display the name of employee Concatinate with Employee Number?
select ename' 'empno from emp;
30) Use appropriate function and extract 3 characters starting from 2 characters from the following string 'Oracle' i.e., the out put should be ac?
select substr('Oracle',3,2) from dual;
31) Find the first occurance of character a from the following string Computer Maintenance Corporation?
select lstr('Computer Maintenance Corporation','a' ) from dual;
32) Replace every occurance of alphabet A with B in the string .Alliens (Use Translate function)
select translate('Alliens','A','B') from Dual;
33) Display the information from the employee table . where ever job Manager is found it should be displayed as Boss?
select ename ,replace(job,'MANAGER','BOSS') from emp;
34) Display empno,ename,deptno from emp table. Instead of display department numbers display the related department name(Use decode function)?
select empno,ename,deptno,Decode(deptno,10,'ACCOUNTING',20, 'RESEARCH' ,30 , 'SALES','OPERATIONS')DName from emp;
35) Display your Age in Days?
select sysdate-to_date('30-jul-1977') from dual;
36) Display your Age in Months?
select months_between(sysdate,to_date('30-jul-1977')) from dual;
37) Display current date as 15th August Friday Nineteen Nienty Seven?
select To_char(sysdate,'ddth Month Day year') from dual;
39) Scott has joined the company on 13th August ninteen ninety?
select empno,ename,to_char(Hiredate,'Day ddth Month year') from emp;
40) Find the nearest Saturday after Current date?
select next_day(sysdate,'Saturday') from dual;
41) Display the current time?
select To_Char(sysdate,'HH:MI:SS') from dual;
42) Display the date three months before the Current date?
select Add_months(sysdate,-3) from dual
43) Display the common jobs from department number 10 and 20?
select job from emp where job in (select job from emp where deptno=20) and deptno=10;
44) Display the jobs found in department 10 and 20 Eliminate duplicate jobs?
select Distinct job from emp where deptno in(10,20);
45) Display the jobs which are unique to department 10?
select job from emp where deptno=10;
46) Display the details of those employees who do not have any person working under him?
select empno,ename,job from emp where empno not in (select mgr from emp where mgr is not null );
47) Display the details of those employees who are in sales department and grade is 3?
select e.ename,d.dname,grade from emp e,dept d ,salgrade where e.deptno=d.deptno and dname='SALES' and grade=3
48) Display thoes who are not managers?
select ename from emp where job!='MANAGER';
49) Display those employees whose name contains not less than 4 characters?
Select ename from emp where length (ename)>=4
50) Display those department whose name start with"S” while location name ends with "K"?
Select e.ename, d.loc from emp e, dept d where d.loc like ('%K') and enamelike ('S%')
51) Display those employees whose manager name is Jones?
Select e.ename Superior, e1.ename Subordinate from emp e, e1 where e.empno = e1.mgr and e.ename='JONES'
52) Display those employees whose salary is more than 3000 after giving 20% increment?
Select ename, sal, (sal+(sal*0.20)) from emp where (sal+(sal*0.20))>3000;
53) Display all employees with their department names?
Select e.ename, d.dname from emp e, dept d where e.deptno=d.deptno
54) Display ename who are working in sales department?
Select e.ename, d.dname from emp e, dept d where e.deptno=d.deptno and d.dname='SALES'
55) Display employee name, dept name, salary, and commission for those sal in between 2000 to 5000 while location is Chicago?
Select e.ename, d.dname, e.sal, e.comm from emp e, dept d where e.deptno=d.deptno and sal between 2000 and 5000
56) Display those employees whose salary is greater than his manager’s salary?
Select e.ename, e.sal, e1.ename, e1.sal from emp e, e1 where e.mgr=e1.empno and e.sal>e1.sal
57) Display those employees who are working in the same dept where his manager is work?
Select e.ename, e.deptno, e1.ename, e1.deptno from emp e, e1 where e.mgr=e1.empno and e.deptno=e1.deptno
58) Display those employees who are not working under any Manager?
Select ename from emp where mgr is null;
59) Display the grade and employees name for the deptno 10 or 30 but grade is not 4 while joined the company before 31-DEC-82?
Select ename, grade, deptno, sal from emp, salgrade where (grade, Sal) in (select grade, Sal from salgrade, emp where sal between losal and hisal) and grade! =4 and deptno in (10,30) and hiredate<'31-Dec-82'
60) Update the salary of each employee by 10% increment that are not eligible for commission?
Update emp set sal= (sal+(sal*0.10)) where comm is null
61) Delete those employees who joined the company before 31-Dec-82 while their department Location is New York or Chicago?
Select e.ename, e.hiredate, d.loc from emp e, dept d where e.deptno=d.deptno and hiredate<'31-Dec-82' and d.loc in('NEW YORK','CHICAGO')
62) Display employee name, job, deptname, and loc for all who are working as manager?
Select e.ename, e.job, d.dname, d.loc from emp e, dept d where e.deptno=d.deptno
and e.empno in (select mgr from emp where mgr is not null)
63) Display those employees whose manager name is Jones and also display their manager name?
Select e.ename sub, e1.ename from emp e, emp e1 where e.mgr=e1.empno and e1.ename='JONES'
64) Display name and salary of ford if his salary is equal to hisal of his grade?
Select ename, grade, hisal, sal from emp, salgrade where ename='FORD' and sal=hisal;
OR
Select grade, sal, hisal from emp, salgrade where ename='FORD' and sal between losal and hisal;
OR
Select ename, sal, hisal, grade from emp, salgrade where ename='FORD' and (grade, Sal) in (select grade, hisal from salgrade,emp where sal between losal and hisal);
65) Display employee name, job, deptname, his manager name, his grade and make an under department wise?
Select e.ename sub, e1.ename sup, e.job, d.dname, grade from emp e1, salgrade, dept d where e.mgr=e1.empno and e.sal between losal and hisal and e.deptno=d.deptno group by d.deptno, e.ename, e1.ename, e.job, d.dname, grade
OR
Select e.ename sub, e1.ename sup, e.job, d.dname, grade from emp e, e1, salgrade, dept d where e.mgr=e1.empno and e.sal between losal and hisal and e.deptno=d.deptno
66) List out all the employee names, job, salary, grade and deptname for every one in a company except ‘CLERK’. Sort on salary display the highest salary?
Select e.ename, e.job, e.sal, d.dname, grade from emp e, salgrade, dept d where (e.deptno=d.deptno and e.sal between losal and hisal) order by e.sal desc
67) Display employee name, job and his manager. Display also employees who are with out managers?
Select e.ename, e1.ename, e.job, e.sal, d.dname from emp e, emp e1, dept d where e.mgr=e1.empno (+) and e.deptno=d.deptno
68) Display Top 5 employee of a Company?

69) Display the names of those employees who are getting the highest salary?
Select ename, sal from emp where sal in (select max (sal) from emp)
70) Display those employees whose salary is equal to average of maximum and minimum?
Select * from emp where sal=(select (max (sal)+min (sal))/2 from emp)
71) Select count of employees in each department where count >3?
Select count (*) from emp group by deptno having count (*)>3
72) Display dname where atleast three are working and display only deptname?
select d.dname from dept d, emp e where e.deptno=d.deptno group by d.dname having count(*)>3
73) Display name of those managers name whose salary is more than average salary of Company?
Select distinct e1.ename, e1.sal from emp e, e1, dept d where e.deptno=d.deptno and e.mgr=e1.empno and e1.sal> (select avg (sal) from emp)

74) Display those managers name whose salary is more than average salary of his employees?
Select distinct e1.ename, e1.sal from emp e, e1, dept d where e.deptno=d.deptno and e.mgr=e1.empno and e1.sal>any (select avg (sal) from emp group by deptno)
75) Display employee name, sal, comm and net pay for those employees whose net pay is greater than or equal to any other employee salary of the company?
Select ename, sal, NVL (comm, 0), sal+NVL (comm, 0) from emp where sal+NVL (comm, 0) >any (select e.sal from emp e)
76) Display those employees whose salary is less than his manager but more than salary of other managers?
Select e.ename sub, e.sal from emp e, e1, dept d where e.deptno=d.deptno and e.mgr=e1.empno and e.salany (select e2.sal from emp e2, e, dept d1 where e.mgr=e2.empno and d1.deptno=e.deptno)
77) Display all employees’ names with total sal of company with each employee name?

78) Find the last 5(least) employees of company?

79) Find out the number of employees whose salary is greater than their managers salary?
Select e.ename, e.sal, e1.ename, e1.sal from emp e, e1, dept d where e.deptno=d.deptno and e.mgr=e1.empno and e.sal>e1.sal
80) Display the manager who are not working under president but they are working under any other manager?
Select e2.ename from emp e1, emp e2, emp e3 where e1.mgr=e2.empno and e2.mgr=e3.empno and e3.job! ='PRESIDENT';
81) Delete those department where no employee working?
Delete from emp where empno is null;
82) Delete those records from emp table whose deptno not available in dept table?
Delete from emp e where e.deptno not in (select deptno from dept)
83) Display those enames whose salary is out of grade available in salgrade table?
Select empno, sal from emp where sal<(select min (LOSAL) from salgrade) OR sal>(select max (hisal) from salgrade)
84) Display employee name, sal, comm and whose net pay is greater than any other in the company?
Select ename, sal, comm, sal+comm from emp where sal+comm>any (select sal+comm from emp)
85) Display name of those employees who are going to retire 31-Dec-99 if maximum job period is 30 years?
Select empno, hiredate, sysdate, to_char (sysdate,'yyyy') - to_char (hiredate,'yyyy') from emp where to_char (sysdate,'yyyy') - to_char (hiredate,'yyyy')=30
86) Display those employees whose salary is odd value?
Select ename, sal from emp where mod (sal, 2)! =0
87) Display those employees whose salary contains atleast 3 digits?
Select ename, sal from emp where length (sal)=3

88) Display those employees who joined in the company in the month of Dec?
Select empno, ename from emp where trim (to_char (hiredate,'Mon'))=trim ('DEC')
89) Display those employees whose name contains A?
Select ename from emp where ename like ('%A%')
90) Display those employees whose deptno is available in salary?
Select ename, sal from emp where deptno in (select distinct sal from emp);
91) Display those employees whose first 2 characters from hiredate - last 2 characters sal?
Select empno, hiredate, sal from emp where trim (substr (hiredate, 1,2))=trim (substr (sal, -2,2));
OR
Select hiredate, sal from emp where to_Char (hiredate,'dd')=trim (substr (sal, -2,2))
92) Display those employees whose 10% of salary is equal to the year joining?
Select ename, sal, 0.10*sal from emp where 0.10*sal=trim (to_char (hiredate,'yy'))
93) Display those employees who are working in sales or research?
Select e.ename from emp e, dept d where e.deptno=d.deptno and d.dname in ('SALES','RESEARCH');
94) Display the grade of Jones?
Select ename, grade from emp, salgrade where (grade, Sal) =(select grade, Sal from salgrade, emp where sal between losal and hisal and ename='JONES')
95) Display those employees who joined the company before 15th of the month?
select ename ,hiredate from emp where hiredate<'15-Jul-02' and hiredate >='01-jul-02';
96) Display those employees who has joined before 15th of the month?
select ename ,hiredate from emp where hiredate<'15-Jul-02'
97) Delete those records where no of employees in particular department is less than 3?
delete from emp where deptno in (select deptno from emp group by deptno having count(*) <3
98) Delete those employeewho joined the company 10 years back from today?
delete from emp where empno in (select empno from emp where to_char(sysdate,'yyyy')- to_char(hiredate,'yyyy')>=10)
99) Display the deptname the number of characters of which is equal to no of employee in any other department?

100) Display the deptname where no employee is working?
select deptno from emp where empno is null;
101) Display those employees who are working as manager?
select e2.ename from emp e1,e2 where e1.mgr=e2.empno and e2.empno is not null
102) Count th number of employees who are working as managers (Using set opetrator)?
select d.dname from dept d where length(d.dname) in (select count(*) from emp e where e.deptno!=d.deptno group by e.deptno)
103) Display the name of the dept those employees who joined the company on the same date?
select a.ename,b.ename from emp a,emp b where a.hiredate=b.hiredate and a.empno!=b.empno
104) Display those employees whose grade is equal to any number of sal but not equal to first number of sal?
select ename,sal,grade ,substr(sal,grade,1) from emp,salgrade where grade!= substr (sal,1,1) and grade = substr(sal,grade,1) and sal between losal and hisal
105) Count the no of employees working as manager using set operation?
Select count(empno) from emp where empno in (select a.empno from emp a intersect select b.mgr from emp b)
106) Display the name of employees who joined the company on the same date?
select a.ename,b.ename from emp a,emp b where a.hiredate=b.hiredate and a.empno!=b.empno;
107) Display the manager who is having maximum number of employees working under him?
select e2.ename,count(*) from emp e1,e2 where e1.mgr=e2.empno group by e2.ename Having count(*)=(select max(count(*)) from emp e1,e2 where e1.mgr=e2.empno group by e2.ename)
108) List out the employee name and salary increased by 15% and express as whole number of Dollars?
select ename,sal,lpad(translate(sal,sal,((sal +(sal*0.15))/50)),5,'$') from emp
147) Produce the output of the emptable "EMPLOYEE_AND JOB" for ename and job ?
Ans: select ename"EMPLOYEE_AND",job"JOB" FROM EMP;
148) List of employees with hiredate in the format of 'June 4 1988'?
Ans: select ename,to_char(hiredate,'Month dd yyyy') from emp;
149) print list of employees displaying 'Just salary' if more than 1500 if exactly 1500 display 'on taget' if less than 1500 display below 1500?
Ans: select ename,sal,
(
case when sal < 1500 then
'Below_Target'
when sal=1500 then
'On_Target'
when sal > 1500 then
'Above_Target'
else
'kkkkk'
end
)
from emp
150) Which query to calculate the length of time any employee has been with the company
Ans: select hiredate, to_char (hiredate,' HH:MI:SS') FROM emp
151) Given a string of the format 'nn/nn' . Verify that the first and last 2 characters are numbers. And that the middle character is '/' Print the expressions 'Yes' IF valid ‘NO’ of not valid. Use the following values to test your solution'12/54', 01/1a, '99/98'?
Ans:

152) Employes hire on OR Before 15th of any month are paid on the last friday of that month those hired after 15th are paid the last friday of th following month .print a list of employees .their hiredate and first pay date sort those who se salary contains first digit of their deptno?
Ans: select ename,hiredate, LAST_DAY ( next_day(hiredate,'Friday')),
(
case when to_char(hiredate,'dd') <=('15') then
LAST_DAY ( next_day(hiredate,'Friday'))
when to_char(hiredate,'dd')>('15') then
LAST_DAY( next_day(add_months(hiredate,1),'Friday'))
end
)
from emp

153) Display those managers who are getting less than his employees salary?
Ans: select a.empno, a.ename, a.sal, b.sal, b.empno, b.ename from emp a, emp b where a.mgr=b.empno and a.sal>b.sal

154) Print the details of employees who are subordinates to BLAKE?
Ans: select a.empno,a.ename ,b.ename from emp a, emp b where a.mgr=b.empno
and b.ename='BLAKE'

Tuesday, November 18, 2008

RECORD BUILTINS



CLEAR_RECORD
Description
Creates a new record in the current block after the current record. Form Builder then navigates to the new record.
Example clear_record;
CREATE RECORD
Description
Creates a new record in the current block after the current record. Form Builder then navigates to the new record.
Example create_record;
DELETE RECORD
Description
When used outside an On-Delete trigger, removes the current record from the block and marks the record as a delete.
Records removed with this built-in are not removed one at a time, but are added to a list of records that are deleted during
the next available commit process.
If the record corresponds to a row in the database, Form Builder locks the record before removing it and marking it as a
delete.
If a query is open in the block, Form Builder fetches a record to refill the block if necessary. See also the description for the
CLEAR_RECORD built-in subprogram.
BEGIN
Delete_Record;
END;
FIRST RECORD
Description
Navigates to the first record in the block's list of records.
Example first_record;
LAST RECORD
Description
Navigates to the last record in the block's list of records. If a query is open in the block, Form Builder fetches the remaining
selected records into the block's list of records, and closes the query.
Example last_record;
NEXT RECORD
Description
Navigates to the first enabled and navigable item in the record with the next higher sequence number than the current record.
If there is no such record, Form Builder will fetch or create a record. If the current record is a new record, NEXT_RECORD
fails.
Example next_record;
PREVIOUS RECORD
Description
Navigates to the first enabled and navigable item in the record with the next lower sequence number than the current record.
Example Previous_record;
SCROLL DOWN
Description
Scrolls the current block's list of records so that previously hidden records with higher sequence numbers are displayed. If
there are available records and a query is open in the block, Form Builder fetches records during SCROLL_DOWN processing.
In a single-line block, SCROLL_DOWN displays the next record in the block's list of records. SCROLL_DOWN puts the input
focus in the instance of the current item in the displayed record with the lowest sequence number.
Scroll_Down;
SCROLL UP
Description
Scrolls the current block's list of records so that previously hidden records with lower sequence numbers are displayed. This
action displays records that were "above" the block's display.
SCROLL_UP puts the input focus in the instance of the current item in the displayed record that has the highest sequence
number.
BEGIN
Scroll_up;
END;
SELECT RECORD
Description
When called from an On-Select trigger, initiates default Form Builder SELECT processing. This built-in is included primarily for
applications that run against a non-ORACLE data source, and use transactional triggers to replace default Form Builder
transaction processing.
Example
Select_record;
UP BUILT IN
Description
Navigates to the instance of the current item in the record with the next lowest sequence number.
Example up;
DOWN BUILT IN
Description
Navigates to the instance of the current item in the record with the next higher sequence number. If necessary, Form Builder
fetches a record. If Form Builder has to create a record, DOWN navigates to the first navigable item in the record.
Example down;
LOCK RECORD
Description
Attempts to lock the row in the database that corresponds to the current record. LOCK_RECORD locks the record
immediately, regardless of whether the Locking Mode block property is set to Immediate (the default) or Delayed.
When executed from within an On-Lock trigger, LOCK_RECORD initiates default database locking. The following example
illustrates this technique.
Begin
Lock_record;
End;
UPDATE RECORD
Description
When called from an On-Update trigger, initiates the default Form Builder processing for updating a record in the database
during the Post and Commit Transaction process.
This built-in is included primarily for applications that run against a non-ORACLE data source.
Begin
Update_record;
End;

OM Cycles

OM Cycles



Sunday, September 14, 2008

SQL Interview Questions


1. The most important DDL statements in SQL are:
CREATE TABLE - creates a new database table
ALTER TABLE - alters (changes) a database table
DROP TABLE - deletes a database table
TRUNCATE - cleans all data
RENAME- renames a table name

2. Operators used in SELECT statements.
= Equal
<> or != Not equal
> Greater than
<>= Greater than or equal
<= Less than or equal BETWEEN Between an inclusive range LIKE Search for a pattern

3. SELECT statements:
SELECT column_name(s) FROM table_name
SELECT DISTINCT column_name(s) FROM table_name
SELECT column FROM table WHERE column operator value
SELECT column FROM table WHERE column LIKE pattern
SELECT column,SUM(column) FROM table GROUP BY column
SELECT column,SUM(column) FROM table GROUP BY column HAVING SUM(column) condition value
Note that single quotes around text values and numeric values should not be enclosed in quotes. Double quotes may be acceptable in some databases.

4. The SELECT INTO Statement is most often used to create backup copies of tables or for archiving records.
SELECT column_name(s) INTO newtable [IN externaldatabase] FROM source
SELECT column_name(s) INTO newtable [IN externaldatabase] FROM source WHERE column_name operator value

5. The INSERT INTO Statements:
INSERT INTO table_name VALUES (value1, value2,....)
INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,....)

6. The Update Statement:
UPDATE table_name SET column_name = new_value WHERE column_name = some_value

7. The Delete Statements:
DELETE FROM table_name WHERE column_name = some_value
Delete All Rows:
DELETE FROM table_name or DELETE * FROM table_name

8. Sort the Rows:
SELECT column1, column2, ... FROM table_name ORDER BY columnX, columnY, ..
SELECT column1, column2, ... FROM table_name ORDER BY columnX DESC
SELECT column1, column2, ... FROM table_name ORDER BY columnX DESC, columnY ASC

9. The IN operator may be used if you know the exact value you want to return for at least one of the columns.
SELECT column_name FROM table_name WHERE column_name IN (value1,value2,..)

10. BETWEEN ... AND
SELECT column_name FROM table_name WHERE column_name BETWEEN value1 AND value2 The values can be numbers, text, or dates.

11. What is the use of CASCADE CONSTRAINTS?
When this clause is used with the DROP command, a parent table can be dropped even when a child table exists.

12. Why does the following command give a compilation error?
DROP TABLE &TABLE NAME; Variable names should start with an alphabet. Here the table name starts with an '&' symbol.

13. Which system tables contain information on privileges granted and privileges obtained? USER_TAB_PRIVS_MADE, USER_TAB_PRIVS_RECD

14. Which system table contains information on constraints on all the tables created?obtained? USER_CONSTRAINTS.

15. State true or false. !=, <>, ^= all denote the same operation?
True.

16. State true or false. EXISTS, SOME, ANY are operators in SQL?
True.

17. What will be the output of the following query?
SELECT REPLACE(TRANSLATE(LTRIM(RTRIM('!! ATHEN !!','!'), '!'), 'AN', '**'),'*','TROUBLE') FROM DUAL;?

18. What does the following query do?
SELECT SAL + NVL(COMM,0) FROM EMP;?
This displays the total salary of all employees. The null values in the commission column will be replaced by 0 and added to salary.

19. What is the advantage of specifying WITH GRANT OPTION in the GRANT command?
The privilege receiver can further grant the privileges he/she has obtained from the owner to any other user.

20. Which command executes the contents of a specified file?
START or @.

21. What is the value of comm and sal after executing the following query if the initial value of ‘sal’ is 10000
UPDATE EMP SET SAL = SAL + 1000, COMM = SAL*0.1;?
sal = 11000, comm = 1000.

22. Which command displays the SQL command in the SQL buffer, and then executes it?
RUN.

23. What command is used to get back the privileges offered by the GRANT command?
REVOKE.

24. What will be the output of the following query? SELECT DECODE(TRANSLATE('A','1234567890','1111111111'), '1','YES', 'NO' );? NO.
Explanation : The query checks whether a given string is a numerical digit.

26. Which date function is used to find the difference between two dates?
MONTHS_BETWEEN.

27. What operator performs pattern matching?
LIKE operator.

28. What is the use of the DROP option in the ALTER TABLE command?
It is used to drop constraints specified on the table.

29. What operator tests column for the absence of data?
IS NULL operator.

30. What are the privileges that can be granted on a table by a user to others?
Insert, update, delete, select, references, index, execute, alter, all.

31. Which function is used to find the largest integer less than or equal to a specific value?
FLOOR.

32. Which is the subset of SQL commands used to manipulate Oracle Database structures, including tables?
Data Definition Language (DDL).

33. What is the use of DESC in SQL?
DESC has two purposes. It is used to describe a schema as well as to retrieve rows from table in descending order.
Explanation :
The query SELECT * FROM EMP ORDER BY ENAME DESC will display the output sorted on ENAME in descending order.

34. What command is used to create a table by copying the structure of another table?
CREATE TABLE .. AS SELECT command
Explanation:
To copy only the structure, the WHERE clause of the SELECT command should contain a FALSE statement as in the following.
CREATE TABLE NEWTABLE AS SELECT * FROM EXISTINGTABLE WHERE 1=2;
If the WHERE condition is true, then all the rows or rows satisfying the condition will be copied to the new table.

35. TRUNCATE TABLE EMP;DELETE FROM EMP;
Will the outputs of the above two commands differ?
Both will result in deleting all the rows in the table EMP..

36. What is the output of the following query SELECT TRUNC(1234.5678,-2) FROM DUAL;?
1200.

37. What are the wildcards used for pattern matching.?
_ for single character substitution and % for multi-character substitution.

38. What is the parameter substitution symbol used with INSERT INTO command?
&

39. What's an SQL injection?
SQL Injection is when form data contains an SQL escape sequence and injects a new SQL query to be run.

40. What is difference between TRUNCATE & DELETE
TRUNCATE commits after deleting entire table i.e., cannot 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.

41. 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 retrieve rows that do not have corresponding join value in the other table.

42. What is the sub-query?
Sub-query is a query whose return values are used in filtering conditions of the main query.

43. What is correlated sub-query?
Correlated sub-query is a sub-query, which has reference to the main query.

44. Explain CONNECT BY PRIOR?
Retrieves rows in hierarchical order eg.
select empno, ename from emp where.

45. Difference between SUBSTR and INSTR?
INSTR (String1, String2 (n, (m)),
INSTR returns the position of the m-th 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 n-th position of string1.

46. Explain UNION, MINUS, UNION ALL and 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 query
UNION ALL - returns all rows selected by either query, including all duplicates.

47. What is ROWID?
ROWID is a pseudo column attached to each row of a table. It is 18 characters long, blockno, rownumber are the components of ROWID.

48. What is the fastest way of accessing a row in a table?
Using ROWID.
CONSTRAINTS

49. What is an integrity constraint?
Integrity constraint is a rule that restricts values to a column in a table.

50. What is referential integrity constraint?
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.

51. 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.

52. 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.

53. What are the data types allowed in a table?
CHAR, VARCHAR2, NUMBER, DATE, RAW, LONG and LONG RAW.

54. 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 the maximum length is 255 and 2000 for VARCHAR2.

55. 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 column is allowed. It is not possible to use LONG column in WHERE or ORDER BY clause.

56. What are the pre-requisites to modify datatype of a column and 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.

57. Where the integrity constraints are stored in data dictionary?
The integrity constraints are stored in USER_CONSTRAINTS.

58. How will you activate/deactivate integrity constraints?
The integrity constraints can be enabled or disabled by ALTER TABLE ENABLE CONSTRAINT / DISABLE CONSTRAINT.

59. If 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.

60. What is a database link?
Database link is a named path through which a remote database can be accessed.

61. 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.

62.What is CYCLE/NO CYCLE in a Sequence?
CYCLE specifies that the sequence continue 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.

63. 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.

64. 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.

65. 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 and these tables are the base tables of a view, then the changes will be reference on the view.

66. Which of the following statements is true about implicit cursors?
1. Implicit cursors are used for SQL statements that are not named.
2. Developers should use implicit cursors with great care.
3. Implicit cursors are used in cursor for loops to handle data processing.
4. Implicit cursors are no longer a feature in Oracle.

67. Which of the following is not a feature of a cursor FOR loop?
1. Record type declaration.
2. Opening and parsing of SQL statements.
3. Fetches records from cursor.
4. Requires exit condition to be defined.

66. A developer would like to use referential datatype declaration on a variable. The variable name is EMPLOYEE_LASTNAME, and the corresponding table and column is EMPLOYEE, and LNAME, respectively. How would the developer define this variable using referential datatypes?
1. Use employee.lname%type.
2. Use employee.lname%rowtype.
3. Look up datatype for EMPLOYEE column on LASTNAME table and use that.
4. Declare it to be type LONG.

67. Which three of the following are implicit cursor attributes?
1. %found
2. %too_many_rows
3. %notfound
4. %rowcount
5. %rowtype

68. If left out, which of the following would cause an infinite loop to occur in a simple loop?
1. LOOP
2. END LOOP
3. IF-THEN
4. EXIT

69. Which line in the following statement will produce an error?
1. cursor action_cursor is
2. select name, rate, action
3. into action_record
4. from action_table;
5. There are no errors in this statement.

70. The command used to open a CURSOR FOR loop is
1. open
2. fetch
3. parse
4. None, cursor for loops handle cursor opening implicitly.

71. What happens when rows are found using a FETCH statement
1. It causes the cursor to close
2. It causes the cursor to open
3. It loads the current row values into variables
4. It creates the variables to hold the current row values

72. Read the following code:
10. CREATE OR REPLACE PROCEDURE find_cpt
11. (v_movie_id {Argument Mode} NUMBER, v_cost_per_ticket {argument mode} NUMBER)
12. IS
13. BEGIN
14. IF v_cost_per_ticket > 8.5 THEN
15. SELECT cost_per_ticket
16. INTO v_cost_per_ticket
17. FROM gross_receipt
18. WHERE movie_id = v_movie_id;
19. END IF;
20. END;
Which mode should be used for V_COST_PER_TICKET?
1. IN
2. OUT
3. RETURN
4. IN OUT
73. Read the following code:
22. CREATE OR REPLACE TRIGGER update_show_gross
23. {trigger information}
24. BEGIN
25. {additional code}
26. END;
The trigger code should only execute when the column, COST_PER_TICKET, is greater than $3. Which trigger information will you add?
1. WHEN (new.cost_per_ticket > 3.75)
2. WHEN (:new.cost_per_ticket > 3.75
3. WHERE (new.cost_per_ticket > 3.75)
4. WHERE (:new.cost_per_ticket > 3.75)

74. What is the maximum number of handlers processed before the PL/SQL block is exited when an exception occurs?
1. Only one
2. All that apply
3. All referenced
4. None

77. For which trigger timing can you reference the NEW and OLD qualifiers?
1. Statement and Row 2. Statement only 3. Row only 4. Oracle Forms trigger

78. Read the following code:
CREATE OR REPLACE FUNCTION get_budget(v_studio_id IN NUMBER)
RETURN number IS
v_yearly_budget NUMBER;
BEGIN
SELECT yearly_budget
INTO v_yearly_budget
FROM studio
WHERE id = v_studio_id;
RETURN v_yearly_budget;
END;
Which set of statements will successfully invoke this function within SQL*Plus?
1. VARIABLE g_yearly_budget NUMBER
EXECUTE g_yearly_budget := GET_BUDGET(11);
2. VARIABLE g_yearly_budget NUMBER
EXECUTE :g_yearly_budget := GET_BUDGET(11);
3. VARIABLE :g_yearly_budget NUMBER
EXECUTE :g_yearly_budget := GET_BUDGET(11);
4. VARIABLE g_yearly_budget NUMBER
31. CREATE OR REPLACE PROCEDURE update_theater
32. (v_name IN VARCHAR v_theater_id IN NUMBER) IS
33. BEGIN
34. UPDATE theater
35. SET name = v_name
36. WHERE id = v_theater_id;
37. END update_theater;

79. When invoking this procedure, you encounter the error:
ORA-000:Unique constraint(SCOTT.THEATER_NAME_UK) violated.
How should you modify the function to handle this error?
1. An user defined exception must be declared and associated
with the error code and handled in the EXCEPTION section.
2. Handle the error in EXCEPTION section by referencing the error
code directly.
3. Handle the error in the EXCEPTION section by referencing the UNIQUE_ERROR predefined exception.
4. Check for success by checking the value of SQL%FOUND immediately after the UPDATE statement.

80. Read the following code:
40. CREATE OR REPLACE PROCEDURE calculate_budget IS
41. v_budget studio.yearly_budget%TYPE;
42. BEGIN
43. v_budget := get_budget(11);
44. IF v_budget < 30000
45. THEN
46. set_budget(11,30000000);
47. END IF;
48. END; You are about to add an argument to CALCULATE_BUDGET.
What effect will this have?
1. The GET_BUDGET function will be marked invalid and must be recompiled before the next execution.
2. The SET_BUDGET function will be marked invalid and must be recompiled before the next execution.
3. Only the CALCULATE_BUDGET procedure needs to be recompiled.
4. All three procedures are marked invalid and must be recompiled.

81. Which procedure can be used to create a customized error message?
1. RAISE_ERROR
2. SQLERRM
3. RAISE_APPLICATION_ERROR
4. RAISE_SERVER_ERROR

82. The CHECK_THEATER trigger of the THEATER table has been disabled. Which command can you issue to enable this trigger?
1. ALTER TRIGGER check_theater ENABLE;
2. ENABLE TRIGGER check_theater;
3. ALTER TABLE check_theater ENABLE check_theater;
4. ENABLE check_theater;

83. Examine this database trigger
52. CREATE OR REPLACE TRIGGER prevent_gross_modification
53. {additional trigger information}
54. BEGIN
55. IF TO_CHAR(sysdate, DY) = MON
56. THEN
57. RAISE_APPLICATION_ERROR(-20000,Gross receipts cannot be deleted on Monday);
58. END IF;
59. END;
This trigger must fire before each DELETE of the GROSS_RECEIPT table. It should fire only once for the entire DELETE statement. What additional information must you add?
1. BEFORE DELETE ON gross_receipt
2. AFTER DELETE ON gross_receipt
3. BEFORE (gross_receipt DELETE)
4. FOR EACH ROW DELETED FROM gross_receipt

84. Examine this function:
61. CREATE OR REPLACE FUNCTION set_budget
62. (v_studio_id IN NUMBER, v_new_budget IN NUMBER) IS
63. BEGIN
64. UPDATE studio
65. SET yearly_budget = v_new_budget WHERE id = v_studio_id; IF SQL%FOUND THEN RETURN TRUEl; ELSE RETURN FALSE; END IF; COMMIT; END; Which code must be added to successfully compile this function?
1. Add RETURN right before the IS keyword.
2. Add RETURN number right before the IS keyword.
3. Add RETURN boolean right after the IS keyword.
4. Add RETURN boolean right before the IS keyword.

85. Under which circumstance must you recompile the package body after recompiling the package specification?
1. Altering the argument list of one of the package constructs
2. Any change made to one of the package constructs
3. Any SQL statement change made to one of the package constructs
4. Removing a local variable from the DECLARE section of one of the package constructs

86. Procedure and Functions are explicitly executed. This is different from a database trigger. When is a database trigger executed?
1. When the transaction is committed
2. During the data manipulation statement
3. When an Oracle supplied package references the trigger
4. During a data manipulation statement and when the transaction is committed

87. Which Oracle supplied package can you use to output values and messages from database triggers, stored procedures and functions within SQL*Plus?
1. DBMS_DISPLAY
2. DBMS_OUTPUT
3. DBMS_LIST
4. DBMS_DESCRIBE

88. What occurs if a procedure or function terminates with failure without being handled?
1. Any DML statements issued by the construct are still pending and can be committed or rolled back.
2. Any DML statements issued by the construct are committed
3. Unless a GOTO statement is used to continue processing within the BEGIN section,the construct terminates.
4. The construct rolls back any DML statements issued and returns the unhandled exception to the calling environment.

89. Examine this code
71. BEGIN
72. theater_pck.v_total_seats_sold_overall := theater_pck.get_total_for_year;
73. END; For this code to be successful, what must be true?
1. Both the V_TOTAL_SEATS_SOLD_OVERALL variable and the GET_TOTAL_FOR_YEAR function must exist only in the body of the THEATER_PCK package.
2. Only the GET_TOTAL_FOR_YEAR variable must exist in the specification of the THEATER_PCK package.
3. Only the V_TOTAL_SEATS_SOLD_OVERALL variable must exist in the specification of the THEATER_PCK package.
4. Both the V_TOTAL_SEATS_SOLD_OVERALL variable and the GET_TOTAL_FOR_YEAR function must exist in the specification of the THEATER_PCK package.

90. A stored function must return a value based on conditions that are determined at runtime. Therefore, the SELECT statement cannot be hard-coded and must be created dynamically when the function is executed. Which Oracle supplied package will enable this feature?
1. DBMS_DDL
2. DBMS_DML
3. DBMS_SYN
4. DBMS_SQL

91 How to implement ISNUMERIC function in SQL *Plus ? Method
1: Select length (translate(trim (column_name),'+-.0123456789',''))from dual; Will give you a zero if it is a number or greater than zero if not numeric (actually gives the count of non numeric characters) Method 2: select instr(translate('wwww','abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ','XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXX'),'X') FROM dual; It returns 0 if it is a number, 1 if it is not.

92 How to Select last N records from a Table? select * from (select rownum a, CLASS_CODE,CLASS_DESC from clm) where a > ( select (max(rownum)-10) from clm) Here N = 10
The following query has a Problem of performance in the execution of the following
query where the table ter.ter_master have 22231 records. So the results are obtained
after hours.
Cursor rem_master(brepno VARCHAR2) IS
select a.* from ter.ter_master a
where NOT a.repno in (select repno from ermast) and
(brepno = 'ALL' or a.repno > brepno)
Order by a.repno
What are steps required tuning this query to improve its performance?
-Have an index on TER_MASTER.REPNO and one on ERMAST.REPNO
-Be sure to get familiar with EXPLAIN PLAN. This can help you determine the execution
path that Oracle takes. If you are using Cost Based Optimizer mode, then be sure that
your statistics on TER_MASTER are up-to-date. -Also, you can change your SQL to:
SELECT a.*
FROM ter.ter_master a
WHERE NOT EXISTS (SELECT b.repno FROM ermast b
WHERE a.repno=b.repno) AND
(a.brepno = 'ALL' or a.repno > a.brepno)
ORDER BY a.repno;

93. What is the difference between Truncate and Delete interms of Referential Integrity?
DELETE removes one or more records in a table, checking referential Constraints (to see if there are dependent child records) and firing any DELETE triggers. In the order you are deleting (child first then parent) There will be no problems.
TRUNCATE removes ALL records in a table. It does not execute any triggers. Also, it
only checks for the existence (and status) of another foreign key Pointing to the
table. If one exists and is enabled, then you will get The following error. This
is true even if you do the child tables first.
ORA-02266: unique/primary keys in table referenced by enabled foreign keys
You should disable the foreign key constraints in the child tables before issuing
the TRUNCATE command, then re-enable them afterwards.

PL-SQL Interview Questions

1. Describe the difference between a procedure, function and anonymous pl/sql block.
Level: Low
Expected answer : Candidate should mention use of DECLARE statement, a function must
return a value while a procedure doesn?t have to.

2. What is a mutating table error and how can you get around it?
Level: Intermediate
Expected answer: This happens with triggers. It occurs because the trigger is trying
to update a row it is currently using. The usual fix involves either use of views
or temporary tables so the database is selecting from one while updating the other.

3. Describe the use of %ROWTYPE and %TYPE in PL/SQL
Level: Low
Expected answer: %ROWTYPE allows you to associate a variable with an entire table row.
The %TYPE associates a variable with a single column type.

4. What packages (if any) has Oracle provided for use by developers?
Expected answer: Oracle provides the DBMS_ series of packages. There are many
which developers should be aware of such as DBMS_SQL, DBMS_PIPE, DBMS_TRANSACTION,
DBMS_LOCK, DBMS_ALERT, DBMS_OUTPUT, DBMS_JOB, DBMS_UTILITY, DBMS_DDL, UTL_FILE. If
they can mention a few of these and describe how they used them, even better. If
they include the SQL routines provided by Oracle, great, but not really what
was asked.

5. Describe the use of PL/SQL tables
Expected answer: PL/SQL tables are scalar arrays that can be referenced by a
binary integer. They can be used to hold values for use in later queries
or calculations. In Oracle 8 they will be able to be of the %ROWTYPE designation,
or RECORD.

6. When is a declare statement needed ?
The DECLARE statement is used in PL/SQL anonymous blocks such as with stand alone, non-stored PL/SQL procedures. It must come first in a PL/SQL stand alone file if it is used.

7. In what order should a open/fetch/loop set of commands in a PL/SQL block be implemented if you use the NOTFOUND cursor variable in the exit when statement? Why?
Expected answer: OPEN then FETCH then LOOP followed by the exit when. If not specified in this order will result in the final return being done twice because of the way the %NOTFOUND is handled by PL/SQL.

8. What are SQLCODE and SQLERRM and why are they important for PL/SQL developers?
Expected answer: SQLCODE returns the value of the error number for the last error encountered. The SQLERRM returns the actual error message for the last error encountered. They can be used in exception handling to report, or, store in an error log table, the error that occurred in the code. These are especially useful for the WHEN OTHERS exception.

9. How can you find within a PL/SQL block, if a cursor is open?
Expected answer: Use the %ISOPEN cursor status variable.

10. How can you generate debugging output from PL/SQL?
Expected answer: Use the DBMS_OUTPUT package. Another possible method is to just use the SHOW ERROR command, but this only shows errors. The DBMS_OUTPUT package can be used to show intermediate results from loops and the status of variables as the procedure is executed. The new package UTL_FILE can
also be used.

11. What are the types of triggers?
Expected Answer: There are 12 types of triggers in PL/SQL that consist of
combinations of the BEFORE, AFTER, ROW, TABLE, INSERT, UPDATE, DELETE and
ALL key words:
BEFORE ALL ROW INSERT
AFTER ALL ROW INSERT
BEFORE INSERT
AFTER INSERT etc.

SQL / SQLPlus Interview Questions

1. How can variables be passed to a SQL routine?
Expected answer: By use of the & symbol. For passing in variables the numbers
1-8 can be used (&1, &2,...,&8) to pass the values after the command into the
SQLPLUS session. To be prompted for a specific variable, place the ampersanded
variable in the code itself:
"select * from dba_tables where owner=&owner_name;" . Use of double
ampersands tells SQLPLUS to resubstitute the value for each subsequent
use of the variable, a single ampersand will cause a reprompt for the
value unless an ACCEPT statement is used to get the value from the user.

2. You want to include a carriage return/linefeed in your output from a SQL script, how can you do this?
Expected answer: The best method is to use the CHR() function (CHR(10) is a return/linefeed) and the concatenation function "". Another method, although it is hard to document and isn?t always portable is to use the return/linefeed as a part of a quoted string.

3. How can you call a PL/SQL procedure from SQL?
Expected answer: By use of the EXECUTE (short form EXEC) command.

4. How do you execute a host operating system command from within SQL?
Expected answer: By use of the exclamation point "!" (in UNIX and some other OS) or the HOST (HO) command.

5. You want to use SQL to build SQL, what is this called and give an example
Expected answer: This is called dynamic SQL. An example would be:
set lines 90 pages 0 termout off feedback off verify off
spool drop_all.sql
select ?drop user ?username? cascade;? from dba_users
where username not in ("SYS?,?SYSTEM?);
spool off
Essentially you are looking to see that they know to include a command (in this case DROP USER...CASCADE;) and that you need to concatenate using the ?? the values selected from the database.

6. What SQLPlus command is used to format output from a select?
Expected answer: This is best done with the COLUMN command.

7. You want to group the following set of select returns, what can you group on?
Max(sum_of_cost), min(sum_of_cost), count(item_no), item_no
Expected answer: The only column that can be grouped on is the "item_no" column, the rest have aggregate functions associated with them.

8. What special Oracle feature allows you to specify how the cost based system treats a SQL statement?
Level: Intermediate to high Expected answer: The COST based system allows the use of HINTs to control the optimizer path selection. If they can give some example hints such as FIRST ROWS, ALL ROWS, USING INDEX, STAR, even better.

9. You want to determine the location of identical rows in a table before attempting to place a unique index on the table, how can this be done?
Level: High Expected answer: Oracle tables always have one guaranteed unique column, the rowid column. If you use a min/max function against your rowid and then select against the proposed primary key you can squeeze out the rowids of the duplicate rows pretty quick. For example: select rowid from emp e where e.rowid > (select min(x.rowid) from emp x where x.emp_no = e.emp_no); In the situation where multiple columns make up the proposed key, they must all be used in the where clause.

10. What is a Cartesian product?
Expected answer: A Cartesian product is the result of an unrestricted join of two or more tables. The result set of a three table Cartesian product will have x * y * z number of rows where x, y, z correspond to the number of rows in each table involved in the join.

11. You are joining a local and a remote table, the network manager complains about the traffic involved, how can you reduce the network traffic?
Level: High Expected answer: Push the processing of the remote data to the remote instance by using a view to pre-select the information for the join. This will result in only the data required for the join being sent across.

12. What is the default ordering of an ORDER BY clause in a SELECT statement?
Expected answer: Ascending

13. What is tkprof and how is it used?
Level: Intermediate to high Expected answer: The tkprof tool is a tuning tool used to determine cpu and execution times for SQL statements. You use it by first setting timed_statistics to true in the initialization file and then turning on tracing for either the entire database via the sql_trace parameter or for the session using the ALTER SESSION command. Once the trace file is generated you run the tkprof tool against the trace file and then look at the output from the tkprof tool. This can also be used to generate explain plan output.

14. What is explain plan and how is it used?
Level: Intermediate to high Expected answer: The EXPLAIN PLAN command is a tool to tune SQL statements. To use it you must have an explain_table generated in the user you are running the explain plan for. This is created using the utlxplan.sql script. Once the explain plan table exists you run the explain plan command giving as its argument the SQL statement to be explained. The explain_plan table is then queried to see the execution plan of the statement. Explain plans can also be run using tkprof.

15. How do you set the number of lines on a page of output? The width?
Level: Low Expected answer: The SET command in SQLPLUS is used to control the number of lines generated per page and the width of those lines, for example SET PAGESIZE 60 LINESIZE 80 will generate reports that are 60 lines long with a line width of 80 characters. The PAGESIZE and LINESIZE options can be shortened to PAGES and LINES.

16. How do you prevent output from coming to the screen?
Level: Low
Expected answer: The SET option TERMOUT controls output to the screen. Setting TERMOUT OFF turns
off screen output. This option can be shortened to TERM.

17. How do you prevent Oracle from giving you informational messages during and after a SQL statement execution?
Level: Low Expected answer: The SET options FEEDBACK and VERIFY can be set to OFF.

18. How do you generate file output from SQL?
Answer: By use of the SPOOL command

Thursday, September 11, 2008

Customer Interface Diagram

Customer Interface Diagram



Master Detail Forms


1) Create Two Tables (With Parent / Child relationships)

a) Create table orders
(order_no number(10),
custoner varchar2(20),
order_date date)
/
b) Create table lines
( line_no number(10),
order_no number(10),
item varchar2(20),
qty number(10),
price number(10),
amount number(10))
/

2) Alter the table structures and primary and foreign keys
Alter table orders add constraint orders_pk primary key (order_no);
Alter table lines add constraint lines_fk foreign key (order_no) references orders (order_no);

3) Create public synonyms for the tables.
4) Register two tables with constraints information.
5) Open form builder software.
6) Open template.fmb file.
7) Save as è TETMADET.fmb
8) Change form module name as form name.
9) Delete default blocks , canvasses and windows.
10) Create two windows , two canvasses
Window1 : Orders
Window2 : Lines
Canvas1 : Orders
Canvas2 : Lines

11) Assign Canvasses to Windows.
12) Assign Windows to Canvasses.
13) Assign property classes to windows and canvasses.
14) Create Two Blocks
Block1 : Orders Type : Form
Block2 : Lines Type : Tabular No of Records : 5

15) Define master detail block relationship between two blocks .
Relationship Name : Orders_Lines

16) Create a Control Block
17) Create a Check box on detail window/ detail canvas
Block => Control
Name => Orders_lines (Same as your master detail relationship name)
Checked value => Immediate
Unchecked Value => Deferred
Default => Immediate

18) Create a Push button in Master Window / Master Canvas
Name : LINES
Label : Lines ..
Block => Control

19) Assign Text Item property class to all text items on Orders and Lines block.
20) Set Module / Form Level properties
First navigation data block => Orders
Console Window => Orders

21) Modify App_custom Package
Close window procedure
If ( wnd = ‘Orders’) then
App_window.close_first_window;
Elsif (wnd = ‘Lines’) then
App_window.set_coordination(‘WHEN-WINDOW-CLOSED’, :CONTROL.ORDER_LINES (CHECKBOX) , ‘ORDERS_LINES’ (RELATIONSHIP NAME) );
End if;

Open Window Procedure
If (wnd = ‘Orders’) then
Go_block (‘ Orders’) ;
Return;
If (wnd = ‘Lines’) then
App_window.set_coordination (‘ OPEN-WINDOW’, :CONTROL,ORDERS_LINES , ‘ORDERS_LINES’);
Go_block (‘ Lines’);
End if;

22) Create a program unit
Name : Control
Type : Package Spec
Procedure Lines (Event In Varchar2) ;
Procedure Orders_Lines ( Event In Varchar2);

23) Create a program unit
Name : Control
Type : Package Body
Procedure Lines (Event In Varchar2) is
Begin
If (event = ‘ WHEN – BUTTON – PRESSED’ ) then
App_custom.open_window (‘Lines’);
Return;
End if;
End Lines;

Procedure Orders_Lines ( Event In Varchar2) then
Begin
If (Event = ‘ WHEN – CHECKBOX – CHANGED’) then
End if ;
End order_lines;

24) In control block write a WBP trigger on Lines Button.
Control . Lines ( ‘WHEN – BUTTON – PRESSED’);


25) In control block write a WCC trigger on Orders_Lines checkbox.
Control.orders_lines(‘WHEN- CHECKBOX – CHANGED’);

26) Modify PRE – FORM trigger
APP_WINDOW.SET_WINDOW_POSITION(‘ORDERS’,NULL,’ORDERS);

27) Save and Compile .
28) Register the form.

CUSTOM FORM DEVELOPMENT


On the CLIENT machine create a FOLDER as say: c:\custom_sunil

In custom_sunil folder creates 2 folders forms, resource

Copy TEMPLATE.fmb, APPSTAND.fmb, .pll files to CLIENT

• Copy TEMPLATE.fmb , APPSTAND.fmb from AU_TOP/forms/US to c:\custom_sunil\ forms directory copy all .pll files from /Applvis/visappl/au/11.5.0/resource to c:\custom_sunil\resource using ftp
• On windows go to command prompt
• Cd c:\custom_sunil\forms
• ftp cloneserver
• username: applmgr password: applmgr
• now you are at ftp prompt
• bin
• prompt
• cd visappl/au/11.5.0/forms/US ( here apparently cd $AU_TOP does not work)
• get TEMPLATE.fmb
• (file copied)
• get APPSTAND.fmb
• (file copied)
• lcd ./resource (check this. Basically you need to be in c:\custom_sunil\resource. You can go to that directory and then run ftp)
• cd visappl/au/11.5.0/resource
• mget *.pll
• ( now all .pll files are copied to c:custom_sunil/resource)

SET env variable FORMS60_PATH through regedit

• Regedit/HKEY_LOCAL_MACHINE/software/oracle
• Double click FORMS60_PATH
• At the end of existing value data add: ;c:\custom_sunil\froms;c:\custom_sunil\resource

Now open TEMPLATE.fmb and make the following changes

• DELETE BLOCKNAME &DETAIL BLOCK FROM DATABLOCK,DELETE BLOCKNAME FROM CANVAS AND WINDOW
• Create a window NEW_WIN, canvas NEW_CAN
• Create a new block based on the table you created in your custom schema
• In pre-form trigger: app_windows.set_window_position(‘NEW_WIN’)…….
• In program units open custom_package.AP_cutom_pacakge body
• Change : if (wind=’NEW_WIN’);
• Template name = SUNIL_FORM
• Save as SUNIL_FROM to c:\custom_sunil\forms
• (????????SET THE WINDOW NAME AS U HAVE CREATED NEW WINDOW IN PRE-FORM TRIGGER BY BLOCKNAME?????)

DEPLOY the FORM (upload it to AU_TOP/forms/US)

• Go to command prompt (on client)
• cd c:\cutom_sunil\forms
• ftp cloneserver
• cd visappl/au/11.5.0/froms/US
• bin
• prompt
• put SUNIL_FORM.fmb


Changing ORACLE_HOME (/Visdb/visdb/9.2.0 to /Applvis/visora/8.0.6)

• thru putty login as applmgr
• pwd: /Applvis
• echo $ORACLE_HOME: shows /Visdb/visdb/9.2.0
• cd visora
• cd 8.0.6
• . VIS_cloneserver.env (this changes ORACLE_HOME apparently based on pwd?)
• echo $ORACLE_HOME: shows /Applvis/visora/8.0.6
• now ORACLE_HOME is 8.0.6 (forms/reports home)
• pwd : gives /Applvis/visora/8.0.6

COMPILE and generate FMX

• (now you are in /Applvis/visora/8.0.6 directory and ORACLE_HOME is set to /Applvis/visora/8.0.6)
• pwd: gives /Applvis/visora/8.0.6
• f60gen module=$AU_TOP/forms/US/SUNIL_FORMS.fmb module_type=form user=apps output_file=$SUNIL_TOP/forms/US/SRIN_FORM.fmx compile_all=special batch=no
• this generates SUNIL_FORM.fmx and puts in SUNIL_TOP/forms/US

FORM REGISTRATION

• Login to applications with application developer responsibility
• Application/form
• Enter the following details
o Form: the fmx name (SUNIL_FORM)
o Application: Oracle Receivables (as per Amer) –give appropriate name based the intended use of this form
o user form name: SUNIL_FORM_U (this will appear in LOV)
o SAVE

Attach the FORM to FUNCTION
(Create a new function)
Application/function
Enter the following details
o Function: SUNIL_FUNCT
o User function name: SUNIL FUNCTION
o Form: SUNIL_FORM (previously registered)
o SAVE

Attach FUNCTION to MENU
Application/menu
• Enter the following details
o Menu: sunil_menu
o User menu name: sunil menu
o Seq: 1
o Prompt: sunil form
o Function: SUNIL_FUNCT( previously deined)
o SAVE

Attach MENU to RESPONSIBILITY

Attach RESPONSIBILITY to USER

Login as the new USER

• See the form

Wednesday, September 10, 2008

TRIGGERS


TRIGGERS

IT IS A PL/SQL BLOCK OR PL/SQL PROCEDURE ASOCITED WITH A TABLE,VIEW,SCHEMA OR DATABASE EXECUTED AUTOMATICALLY RATHER IN TECHNICAL TERMS IMPLICITLY FIRED AUTOMATICALLY WHENEVER A SPECIFIC EVENT OCCURS UPON THE OBJECT ASSOCIAYED WITH.

TYPES OF TRIGGERS

THERE ARE TWO TYPES OF TRIGGERS.

APPLICATION TRIGGER:-FIRED WHENEVER AN EVENT //CAN BE CONSIDERED AS A DML OPERATION// OCCURS UPON A PARTICULAR APPLICATION.

DATABASE TRIGGER:-FIRED WHENVER AN EVENT (IN THE SENSE ANY DML OPERATION OR ANY SYSTEM EVENT I.E LOGON OR SHUTDOWN) OCCURS ON A SCHEMA OR DATABASE.THESE ARE FIRED IMPLICITLY

INSTEAD OF TRIGGERS

THESE ARE ONLY LIMITED TO THE VIEWS .THE NAME SIGNIFIES THE OPERATION OF THE TRIGGER.TO BE MORE ELABORATIVE WHENEVER A DML IS OPERATED UPON A VIEW THE ACTION IS TAKEN CARE OF BY THE INSTEAD OF TRIGGER.RATHER IF ANY OTHER TRIGGERS ARE ASSOCIATED WITH THAT TABLE THEN THOSE TRIGGER WILL BE FIRED.

WHY THE TRIGGERS ARE DESIGNED?

FOR RELATED TASKS TO BE PERFORMED AND TO CENTRALIZE THE GLOBAL OPERATIONS WHICH TAKES CARE OF THE ACTIONS RATHER CONSIDERING WHATEVER APPLIACTION OR WHOEVER THE USER MAY BE.

CREATING DML TRIGGERS

A TRIGGER CONTAINS

A) TRIGGER TIMING DESCRIBES ABOUT THE FIRING OF THE TRIGGER WRT TRIGGERING EVENT.
B) TRIGGERING EVENT DESCRIBES ABOUT THE DML WHICH IS TO BE TAKEN CARE FOR THE BY ACTIONS TO BE RAISED.
C) TRIGGER TYPE DESCRIBES ABOUT THE NUMBER OF TIMES OF EXECUTION OF TRIGGER.
D) TRIGGER BODY DESCRIBES ABOUT THE ACTIONS TAKEN CARE OF BY THE TRIBGGER.
DML TRGGER COMPONENTS

TRIGGER TIMING

A) BEFORE TRIGGERS EXECUTION OF TRIGGER BOBY OCCURS BEFORE THE DML EVENT IS OPERATED UPON AN OBJECT.
B) AFTER TRIGGERS EXECUTION OF TRIGGER BOBY OCCURS AFTER THE DML EVENT IS OPERATED UPON AN OBJECT.
C) INSTEAD OF SPECIFIES A SEPARATE EXECUTION PROCESS APART FROM THE TRIGGERING STATEMENT.THESE ACT UPON THE VIEWS AND ARE NOT MODIFIABLE.

DESCRIPTIONS

BEFORE TRIGGERS ARE USED TO DETERMINE THE STATUS OF TRIGGER STATEMENT WHETHER TO BE COMPLETED.ALSO BETTER EXPLANATION CAN BE ROLLBACK.ALSO TO FETCH THE COLUMN VALUES PRIOR TO EXECUTION AND TO VALIDATE RULES OF BUSINESS.

AFTER TRIGGERS ARE USED TO COMPLETE THE ACTON BEFORE TRIGGERING ACTION.IF THERE IS A PRESENCE OF A BEFORE TRIGGER THEN TO INITIATE A DIFFERENT ACTION.

INSTEAD OF TRIGGERS ARE USED TO MODIFY THE VIEWS WHICH CANNOT BE MODIFIED BY A SQL DML STATEMENT DUE TO LACK OF MODIFICATION INHERITANCE.THESE WORK IN THE BACKGROUND ACCORDING TO THE DML ACTIONS SPECIFIED IN THE TRIGGERING BODY.

TRIGGERING EVENTS CAN BE SPECIFICALLY LINKED WITH THE DMLS SUCH AS INSERT, UPDATE OR A DELETE.IN CASE OF UPDATE DML THE COLUMN LIST ARE TO SPECIFIED FOR WHICH THE TRIGGERING ACTIONS ARE TO BE TAKEN CARE OF.

TRIGGER TYPE SPECIFIES WHETHER THE TRIGGER IS TO BE FIRED FOR EACH ROW OR FOR MULTIPLE ROWS (STATEMENT TRIGGERS).THERE ARE TWO TYPES OF TRIGGERS.

1) ROW TRIGGERS ARE EXECUTED ONCE FOR EACH ROW RETRIEVED BY THE DML SPECIFIED IN THE STATEMENT.IT IS NOT EXECUTED IF THE STATEMENT DOES NOT RETURN ANY VALUE.IT IS NOT EXECUTED WHEN NO ROWS ARE SELECTED.

2) STATEMENT TRIGGER IS FIRED ONCE ON BEHALF OF THE TRIGGERING EVENT EVEN IF NO ROWS ARE AFFECTED AT ALL.

TRIGGER BODY EXPLAINS ABOUT THE ACTIONS TO BE TAKEN CARE OF BY THE TRIGGER.IT CAN BE PL/SQL BLOCK OR A CALL PROCEDURE.

NOTE
1) WHEN THE TRIGGERING DATA MANIPULATION STATEMENT EFFECTS THE A SINGLE ROW, BOTH THE ROW TRIGGER AND STATEMENT TRIGGER FIRE EXACTLY ONCE PROVIDED THE TYPE OF TRIGGER THAT HAS BEEN MENTIONED IN THE TRIGGER BODY.

2) WHEN A TRIGGERING DATA MANIPULATION STATEMENT AFFECTS MULTIPLE ROWS THEN THE STATEMENT TRIGGER FIRES EXACTLY ONCE AND THE ROW TRIGGER FIRES ONCE FOR EVERY ROWEFFECTED BY THE STATEMENT.

SYNTAX
CREATE TRIGGER
TIMING
EVENT1 OR OR
ON


TRIGGER NAME SHOULD BE UNIQUE COMPARED TO OTHER TRIGGERS.

SPECIFIES THE TIME WHEN THE TRIGGER WILL FIRE
EITHER OR

IDENTIFIES THE DML THAT CAUSES THE TRIGGER TO FIRE.
EITHER ,, OR ALL OF THE THREE.
NAME OF THE TABLE ASSOCIATED WITH THE TRIGGER.

EXPLAINS ABOUT THE ACTIONS PERFORMED.
IT BEGINS WITH A DECALERE AND END OR A CALL OF PROCEDURE.

USING COLUMNS NAMES WITH UPDATE TRIGGERS INCREASE THE PERFORMANCE BECAUSE THE TRIGGER IS FIRED ONLY WHEN THE UPDATION OF CONCERNED COLUMN OCCURS.IT IS NO WHERE CONCERNNED WITH THE UPDATION OF ANY OTHER COLUMNS OF THE DESCRIBED TABLE IN THE TRIGGER.

EXAMPLE:

IN THE DESCRIBED TRIGGER WHICH IMPLEMENTS THE BUSSINESS RULES THAT RESTRICTS THE ACCESS OF DATABASE TABLE AFTER THE OFFICE HOURS AND HOLIDAYS PROVIDED THE WORK DAY CALENDER IS 5 DAYS A WEEK.

CREATE OR REPLACE TRIGGER SECURE_EMPLOYEES
BEFORE INSERT OR DELETE OR UPDATE ON EMPLOYEES
BEGIN
IF (TO_CHAR (SYSDATE,’DY’) IN (‘SAT’,’SUN’)) OR
(TO_CHAR (SYSDATE,’HH24’) NOT BETWEEN ‘08’ AND ‘18’)
THEN
IF INSERTING THEN
RAISE_APPLICATION_ERROR (-20500,’UR STATEMENT’);
ELSIF DELETING THEN
RAISE_APPLICATION_ERROR (-20500,’UR STATEMENT’);
ELSIF UPDATING THEN
RAISE_APPLICATION_ERROR (-20500,’UR STATEMENT’);
ELSE
RAISE_APPLICATION_ERROR (-20500,’UR SATAMENT2’);
END IF;
END IF;
END;

DML ROW TRIGGERS

WE HAVE TO SPECIFY A SPECIAL PHRASE FOR INITIATING A ROW TRIGGER.REFERENING TO THE ABOVE MENTIONED SYNTAX OF TRIGGER AFTER THE TABLE NAME ‘FOR EACH ROW’ PHRASE IF SPECIFIED INDICATES THE TRIGGER TO BE A ROW TRIGGER.HERE THE NEW VALUES AND THE OLD VALUES ARE ALSO REFERED FOR CORELATION BETWEEN THE OLD VALUES AND NEW VALUES.

WE CAN ALSO RESTRICT THE FIRING OF A ROW TRIGGER BY SPECIFING A WHEN CLAUSE AFTER THE PHRASE MENTIONED ABOVE.

EXAMPLE

CREATE OR REPLACE TRIGGER RESTRICT_SALARY
BEFORE INSERT OR UPDATE OF SALARY ON EMPLOYEES
FOR EACH ROW
BEGIN
IF NOT (:NEW.JOB_ID IN (‘AD_PRES’,’AD_VP’))
AND (:NEW.SALARY) > 15000
THEN
RAISE_APPLICATION_ERROR (-20500, )
END IF;
END;

EXPALAINATION

FOR AN UPDATE OR INSERT UPON EMPLOYEES TABLE IF THE JOB_ID SPECIED IS OTHER THAN AD_PRES AND AD_VP AND SALARY SPECIFIED IS GREATER THAN 15000 IN THE CASE TRIGGER IS FIRED.IN STRAIGHT EAPLAINTION THE EMPLOYEES WHICH HAVE A JOB_ID OF AD_PRES AND AD_VP CAN ONLY EARN A SALARY GREATER THAN 15000.

RESTRICTING A ROW TRIGGER

CREATE OR REPLACE TRIGGER RESTRICT_SALARY
BEFORE INSERT OR UPDATE OF SALARY ON EMPLOYEES
FOR EACH ROW
WHEN (NEW.JOB_ID = ‘SA_REP’)
BEGIN
IF INSERTING THEN
: NEW .COMMISSION_PCT:= 0;
ELSIF (:OLD.COMMISSION_PCT) IS NULL THEN
: NEW.COMMISSION_PCT:= 0;
ELSE
: NEW.COMMISSION_PCT:=:OLD.COMMISSION_PCT + 0.05;
END IF;
END;

EXPLAINATION

IF AN INSERT OPERATION IS OPERATED UPON THE EMPLOYEES TABLE WITH A JOB_ID SPECIFIED AS SA_REP AND COMMISSION_PCT WITH SOME VALUE THEN THE TRIGGER RESTRICT_SALARY WILL FIRE CAUSING A INSERTION OF ZERO IN COMMISION_PCT IN THE TABLE. (PLEASE NOTE LINE NO 7).OTHER WISE IF THE JOB IS OTHER THAN SA_REP THEN ROW IS FULLY INSERTED AS DESIRED.

IF AN UPDATE OPERATION IS OPERATED UPON THE TABLE THERE ARE TWO CASES TO BE NOTICED.

1) IF THE OLD VALUE OF COMMISSION_PCT IS A NULL THEN WHILE UPDATION OF SALARY RESTRICT_SALARY WILL FIRE AND THE COMMISSION_PCT WILL BE ASSIGNED A VALUE OF ZERO.(PLEASE SEE LINE NO 9)

2) IF THE OLD VALUE OF COMMISSION_PCT IS NOT NULL THEN RAISE_SALARY WILL FIRE AND NEW VALUE WILL BE WHAT EVER VALUE THAT HAS BEEN SPECIFIED IN THE ACTION.(PLEASE SEE LINE NO 11)
INSTEAD OF TRIGGERS

IF THE MODIFICATION IS REQUIERD TO BE DONE ON THE DATA OWNED BY AN UNUPDATEABLE VIEW I.E (A VIEW CONTAINING THE SET OPERATORS, DISTINCT CLAUSE, GROUP FUNCTIONS, OR JOINS BECOMES AN UNUPDATEABLE VIEW) THEN THE INSTEAD OF TRIGGERS ARE USED WHICH ARE FIRED BY THE ORACLE SERVER WITHOUT EXECUTING THE TRIGGERING STATEMENT OPERATING THE DML UPON THE UNDERLYING TABLES SPECIFIED.

CREATE OR REPLACE TRIGGER
INSTEAD OF
OR OR
ON VIEW_NAME
FOR EACH ROW


IF THE VIEW IS UPDATEABLE AND CONTAINS THE INSTEAD OF TRIGGERS THEN THESE TRIGGERS TAKE PRECEDENCE.
ALSO THE CHECK OPTIONS ARE NOT TAKEN CARE OF AT THE TIME OF FIRING OF INSTEAD OF TRIGGERS.RATHER IF WANTED THEY MUST BE SPECIFIED IN THE BODY OF INSTEAD OF TRIGGER.

SEE FOR MORE DETAILS ORACLE HAND BOOK

MANAGING TRIGGERS

WE CAN ALTER THE STATUS OF A TRIGGER BY DISABLING OR ENABLING IT.
ALTER TRIGGER DISABLE/ENABLE
FOR IN CASE OF TABLE
ALTER TABLE DISABLE/ENABLE ALL TRIGGERS
FOR RECOMPILING THE TRIGGER BODY
ALTER TRIGGER COMPILE
DROPPING A TRIGGER
DROP TRIGGER TRIGGER_NAME

CREATING DATABASE TRIGGERS

FOR CREATING A DATABASE TRIGGER FIRST THE TRIGGER CMPONENTS ARE TO BE DECIDED.

A TRIGGER DEFINED FOR A SYSTEM EVENT CAN BE AT A LEVEL OF DATABASE OR SCHEMA.FOR EXAMPLE THE LOG OFF TRIGGERS OR TRIGGERS INVOLVING DDL STATEMENTS ARE AT A LEVEL OF EITHER SCHEMA OR DATABASE. THE DATABASE SHUTDOWN TRIGGERS ARE AT A LEVEL OF SCHEMA.

TRIGGERS DEFINED AT SCHEMA LEVEL FIRES WHENEVER THE TRIGGERING EVENT INVOLVES THE SCHEMA OR TABLE.WHEREAS THE DATABASE LEVEL TRIGGERS FIRE FOR ALL USERS.

FOR DLL TRIGGERS THE POSSIBLE EVENTS MAY BE

1) CREATE STATEMENT
2) ALTER STATEMENT]
3) OR A DROP STATEMENT

ANY WAY THE CREATE TRIGGER SYNTAX WILL BE REMAINING THE SAME ALL THE TIME.
FOR A TRIGGER INVOLVED IN THE SYSYTEM EVENTS LIKE

1) AFTER SERVERERROR
2) AFTER LOGON
3) BEFORE LOGOFF
4) AFTER STARTUP
5) BEFORE SHUTDOWN

MUTATING TABLE

IT CAN BE DEFINED AS A TABLE BEING MODIFIED BY AN UPDATE, DELETE INSERT STATEMENT OR THE TABLE IS REQUIRED TO BE UPDATE BY THE EFFECTS OF ON DELETE CASCADE REFERENTIAL INTEGRITY ACTION.

A TRIGGERED TABLE IS ALSO A MUTATING ONE AS WELL AS ANY TABLE REFERENCING IT BY FOREIGN KEY CONSTRAINT.

PROTECTING DATA INTEGRITY WITH TRIGGERS

CREATE OR REPLACE CHECK_SALARY
BEFORE UPDATE OF SALARY ON EMPLOYEES
FOR EACH ROW
WHEN (NEW.SALARY)<(OLD.SALARY)
BEGIN
RAISE_APPLICATION_ERROR (-20508,’DECREASE SALARY NOT ALLOWED’)

END;

SNAPSHOT

IT IS A LOCAL COPY OF A TABLE DATATHAT ORIGINATES FROM ONE OR MORE REMOTE MASTER TABLES.THE DATA OF THE SANAPSHOT CAN BE QUERIED BUT NO DML OPERATIONS CAN BE OPERATED UPON A SNAPSHOT.TO KEEP IN PARALLEL WITH THE BASE TABLES THE SNAPSHOT SHOULD BE REFRESHED REGULARLY.

BENEFITS OF DATABASE TRIGGERS

IT PROVIDES US THE IMPROVED DATA SECURITY
IT ALSO FACILIATES IMPROVED DATA INTEGRITY.

THANK YOU

THIS DATA DOES NOT MAKE YOU MASTER IN TRIGGERS.THERE ARE SO MANY CONCEPTS I JUST TRIED MY LEVEL BEST TO CONCENTRATE ON BASICS

All modules Interface Tables

GL INTERFACE TABLES

TNAME TABTYPE
------------------------------ ------- ----------------------
GL_BUDGET_INTERFACE TABLE
GL_DAILY_RATES_INTERFACE TABLE
GL_IEA_INTERFACE TABLE
GL_INTERFACE TABLE
GL_INTERFACE_CONTROL TABLE
GL_INTERFACE_HISTORY TABLE

AP INTERFACE TABLES

TNAME TABTYPE
------------------------------ ------- ------------------------
AP_INTERFACE_CONTROLS TABLE
AP_INTERFACE_REJECTIONS TABLE
AP_INVOICES_INTERFACE TABLE
AP_INVOICE_LINES_INTERFACE TABLE


AR INTERFACE TABLES

TNAME TABTYPE
------------------------------ --------------------------------------
AR_PAYMENTS_INTERFACE_ALL TABLE
AR_TAX_INTERFACE TABLE
HZ_DQM_SYNC_INTERFACE TABLE
HZ_PARTY_INTERFACE TABLE
HZ_PARTY_INTERFACE_ERRORS TABLE
RA_CUSTOMERS_INTERFACE_ALL TABLE
RA_INTERFACE_DISTRIBUTIONS_ALL TABLE
RA_INTERFACE_ERRORS_ALL TABLE
RA_INTERFACE_LINES_ALL TABLE
RA_INTERFACE_SALESCREDITS_ALL TABLE


FA INTERFACE TABLES

TNAME TABTYPE
------------------------------ ------- ----------------------
FA_BUDGET_INTERFACE TABLE
FA_INV_INTERFACE TABLE
FA_PRODUCTION_INTERFACE TABLE
FA_TAX_INTERFACE TABLE

INVENTORY INTERFACE TABLES

TNAME TABTYPE
------------------------------ ------- ------------------------------------
MTL_CC_ENTRIES_INTERFACE TABLE
MTL_CC_INTERFACE_ERRORS TABLE
MTL_CI_INTERFACE TABLE
MTL_CI_XREFS_INTERFACE TABLE
MTL_COPY_ORG_INTERFACE TABLE
MTL_CROSS_REFERENCES_INTERFACE TABLE
MTL_DEMAND_INTERFACE TABLE
MTL_DESC_ELEM_VAL_INTERFACE TABLE
MTL_EAM_ASSET_NUM_INTERFACE TABLE
MTL_EAM_ATTR_VAL_INTERFACE TABLE
MTL_INTERFACE_ERRORS TABLE

TNAME TABTYPE
------------------------------ ------- --------------------------------------
MTL_INTERFACE_PROC_CONTROLS TABLE
MTL_ITEM_CATEGORIES_INTERFACE TABLE
MTL_ITEM_CHILD_INFO_INTERFACE TABLE
MTL_ITEM_REVISIONS_INTERFACE TABLE
MTL_ITEM_SUB_INVS_INTERFACE TABLE
MTL_OBJECT_GENEALOGY_INTERFACE TABLE
MTL_RELATED_ITEMS_INTERFACE TABLE
MTL_RESERVATIONS_INTERFACE TABLE
MTL_RTG_ITEM_REVS_INTERFACE TABLE
MTL_SECONDARY_LOCS_INTERFACE TABLE
MTL_SERIAL_NUMBERS_INTERFACE TABLE

TNAME TABTYPE
------------------------------ ------- ------------------------------------
MTL_SO_RMA_INTERFACE TABLE
MTL_SYSTEM_ITEMS_INTERFACE TABLE
MTL_TRANSACTIONS_INTERFACE TABLE
MTL_TRANSACTION_LOTS_INTERFACE TABLE
MTL_TXN_COST_DET_INTERFACE TABLE

PO INTERFACE TABLES

TNAME TABTYPE
------------------------------ ------- -------------------------
PO_DISTRIBUTIONS_INTERFACE TABLE
PO_HEADERS_INTERFACE TABLE
PO_INTERFACE_ERRORS TABLE
PO_LINES_INTERFACE TABLE
PO_REQUISITIONS_INTERFACE_ALL TABLE
PO_REQ_DIST_INTERFACE_ALL TABLE
PO_RESCHEDULE_INTERFACE TABLE
RCV_HEADERS_INTERFACE TABLE
RCV_LOTS_INTERFACE TABLE
RCV_SERIALS_INTERFACE TABLE
RCV_TRANSACTIONS_INTERFACE TABLE

BOM INTERFACE TABLES

TNAME TABTYPE
------------------------------ ------- ----------------------------------
BOM_BILL_OF_MTLS_INTERFACE TABLE
BOM_INTERFACE_DELETE_GROUPS TABLE
BOM_INVENTORY_COMPS_INTERFACE TABLE
BOM_OP_RESOURCES_INTERFACE TABLE
BOM_OP_ROUTINGS_INTERFACE TABLE
BOM_OP_SEQUENCES_INTERFACE TABLE
BOM_REF_DESGS_INTERFACE TABLE
BOM_SUB_COMPS_INTERFACE TABLE
CST_COMP_SNAP_INTERFACE TABLE
CST_INTERFACE_ERRORS TABLE
CST_ITEM_COSTS_INTERFACE TABLE
CST_ITEM_CST_DTLS_INTERFACE TABLE
CST_PC_COST_DET_INTERFACE TABLE
CST_PC_ITEM_COST_INTERFACE TABLE

WIP INTERFACE TABLES

TNAME TABTYPE
------------------------------ ------- --------------------------
WIP_COST_TXN_INTERFACE TABLE
WIP_INTERFACE_ERRORS TABLE
WIP_JOB_DTLS_INTERFACE TABLE
WIP_JOB_SCHEDULE_INTERFACE TABLE
WIP_MOVE_TXN_INTERFACE TABLE
WIP_SCHEDULING_INTERFACE TABLE
WIP_TXN_INTERFACE_ERRORS TABLE

ORDER MANAGEMENT INTERFACE TABLES

TNAME TABTYPE
------------------------------ ------- -----------------------------------
SO_CONFIGURATIONS_INTERFACE TABLE
SO_HEADERS_INTERFACE_ALL TABLE
SO_HEADER_ATTRIBUTES_INTERFACE TABLE
SO_LINES_INTERFACE_ALL TABLE
SO_LINE_ATTRIBUTES_INTERFACE TABLE
SO_LINE_DETAILS_INTERFACE TABLE
SO_PRICE_ADJUSTMENTS_INTERFACE TABLE
SO_SALES_CREDITS_INTERFACE TABLE
SO_SERVICE_DETAILS_INTERFACE TABLE
WSH_DELIVERIES_INTERFACE TABLE
WSH_FREIGHT_CHARGES_INTERFACE TABLE
WSH_PACKED_CONTAINER_INTERFACE TABLE

Tuesday, September 9, 2008

GL interface Diagram




Trigger Solutions


Problems (For DML Triggers):

Q.1 Keep the backup of department data for DELETE and UPDATE.
Ans: CREATE OR REPLACE TRIGGER dept_backup_trg

AFTER DELETE OR UPDATE ON dept

FOR EACH ROW

BEGIN

INSERT INTO dept_backup (deptno, dname, loc)

VALUES (:OLD.deptno, :OLD.dname, :OLD.loc);

END;


Q.2 Secure emp table from SCOTT user for DELETE or UPDATE of manager and salesman records.
Ans: CREATE OR REPLACE TRIGGER emp_dml_check

BEFORE DELETE OR UPDATE ON emp

FOR EACH ROW

WHEN (USER = 'SCOTT')

BEGIN

IF UPPER(RTRIM(LTRIM(:OLD.JOB))) IN ('MANAGER', 'SALESMAN')

THEN

RAISE_APPLICATION_ERROR

(-20001, 'You can not update or delete MANAGER or SALESMAN records');

END IF;

END;


Q.3 Delete all related employees as soon as dept is deleted from dept table.
Ans: CREATE OR REPLACE TRIGGER Delete_Emp_Trg

AFTER DELETE ON dept

FOR EACH ROW

BEGIN

DELETE FROM emp WHERE deptno = :OLD.deptno;

END;

Problems (For DDL Triggers):

Q.1 Create a DDL trigger to prevent removal of any table under scott schema.
ANS. CREATE OR REPLACE TRIGGER Drop_Check_For_Scott

BEFORE DROP ON scott.SCHEMA

BEGIN

RAISE_APPLICATION_ERROR (-20001, 'No table can not be droped from SCOTT schema');

END;


2. Create a DDL trigger to prevent removal of emp table under scott schema.
ANS. CREATE OR REPLACE TRIGGER Drop_Check_For_Scott_on_Emp

BEFORE DROP ON scott.SCHEMA

BEGIN

IF UPPER(RTRIM(LTRIM(sys.dictionary_obj_name))) = 'EMP'

THEN

RAISE_APPLICATION_ERROR (-20001, 'EMP table can not be droped from SCOTT schema'); END IF;

END;


Q.3 create a DDL trigger to prevent removal of any table under any schema. (User must have ADMINISTER DATABASE TRIGGER privilege).
ANS. CREATE OR REPLACE TRIGGER Drop_Check_For_Any_Table

BEFORE DROP ON DATABASE

BEGIN

IF UPPER(RTRIM(LTRIM(sys.sysevent))) = 'DROP' AND UPPER(RTRIM(LTRIM(sys.dictionary_obj_Type))) = 'TABLE

THEN

RAISE_APPLICATION_ERROR (-20001, 'Drop Table is not allowed under this Database');

END IF;

END;

Problems (For Instead Of Triggers)

1. create a trigger to allow Data Manipulation on EMP and DEPT tables via the View.

1.1 Create a view on emp and dept tables combination.

1.2 Create Instead Of Trigger on the View.
Ans: CREATE OR REPLACE TRIGGER emp_dept_vw_trg

INSTEAD OF INSERT OR DELETE OR UPDATE ON emp_dept_vw

FOR EACH ROW

BEGIN

IF INSERTING = True THEN

INSERT INTO dept (deptno, dname, loc)

VALUES (:NEW.deptno, :NEW.dname, :NEW.loc);

--

INSERT INTO emp (empno, ename, job, mgr, hiredate, sal, comm, deptno)

VALUES (:NEW.empno, :NEW.ename, :NEW.job, :NEW.mgr, :NEW.hiredate, :NEW.sal, :NEW.comm, :NEW.deptno);

--

ELSIF UPDATING = True THEN

UPDATE dept SET dname = :NEW.dname, loc = :NEW.loc WHERE deptno = :NEW.deptno;

--

UPDATE emp SET ename = :NEW.ename, job = :NEW.job, mgr = :NEW.mgr, hiredate = :NEW.hiredate, sal = :NEW.sal, comm = :NEW.comm, deptno = :NEW.deptno WHERE empno = :NEW..empno; ELSE DELETE FROM emp WHERE empno = :OLD.empno; DELETE FROM dept

WHERE deptno = :OLD.deptno;

END IF;

END;

Problems (For Database Events Triggers)
Q.1 Create a trigger that denies login for any user except SYSTEM or INTERNAL users.
Ans. CREATE OR REPLACE TRIGGER check_user_login

AFTER LOGON ON DATABASE

BEGIN ]

IF :sys.login_user NOT IN ('SYS', 'SYSTEM')

THEN

RAISE_APPLICATION_ERROR (-20001, 'You are not allowed to Login');

END IF;

END;


Q.2 Create a trigger to load a package into KEEP buffer as soon as Database is started.
Ans. CREATE OR REPLACE TRIGGER pin_package

AFTER STARTUP ON DATABASE

BEGIN

DBMS_SHARED_POOL.KEEP ('SCOTT.EMP_PG', 'P');

END;