Professional Documents
Culture Documents
Oracle
Oracle
SELECT DEPARTMENT_ID,
MAX(SALARY) HIGHEST_SALARY,
COUNT(1) KEEP(DENSE_RANK LAST ORDER BY SALARY) CNT_HIGH_SAL
FROM EMPLOYEES
GROUP BY DEPARTMENT_ID;
2. Write a query to get the top 2 employees who are earning the highest salary in
each department?
SELECT DEPARTMENT_ID,
EMPLOYEE_ID,
SALARY
FROM
(
SELECT DEPARTMENT_ID,
EMPLOYEE_ID,
SALARY,
ROW_NUMBER() OVER(PARTITION BY DEPARTMENT_ID ORDER BY SALARY DESC ) R
FROM EMPLOYEES
) A
WHERE R <= 2;
4. Write a query to find the employees who are earning more than the average salary
in their department?
SELECT EMPLOYEE_ID,
SALARY
FROM EMPLOYEES E_O
WHERE SALARY >
( SELECT AVG(SALARY) FROM EMPLOYEES E_I
WHERE E_I.DEPARTMENT_ID = E_O.DEPARTMENT_ID );
It is a form of sub query, where the sub query uses the values from the outer query
in its WHERE clause. The sub query runs for each row processed in the outer query.
Question 4 is an example for a correlated sub query.
1. What is a cursor?
Implicit Cursors: Implicit cursors are created by default when DML statements like
INSERT, UPDATE and DELETE are executed in PL/SQL objects.
Explicit Cursors: Explicit cursors must be created by you when executing the select
statements.
%FOUND : Returns true if a DML or SELECT statement affects at least one row.
%NOTFOUND: Returns true if a DML or SELECT statement does not affect at least one
row.
%ROWCOUNT: Returns the number of rows affected by the DML or SELECT statement.
%ISOPEN: Returns true if a cursor is in open state.
%BULK_ROWCOUNT: Similar to %ROWCOUNT, except it is used in bulk operations.
4. What is a private and public procedure?