Friday, July 4, 2025

SQL and PL/SQL Query for the interview - 02 July 2025 - 8

 select * from emp order by deptno, sal desc;


--Maximum Salary

select max(sal) from emp;


--3rd highest salary

select ename, sal, rank from (

select ename, sal, dense_rank() over(order by sal desc) as rank from emp)

where rank=3;


--more than avg of their own demartment


select * from emp e1, 

(select deptno, avg(sal) as avg from emp group by deptno) e2 where e1.deptno=e2.deptno and e1.sal>e2.avg;


--can we user case in where condition

SELECT *

FROM emp

WHERE

  CASE 

    WHEN job = 'MANAGER' THEN 1

    WHEN sal > 100000 THEN 2

    ELSE 0

  END = 2;

  

--Can we use decode in where condition

SELECT *

FROM emp

WHERE DECODE(deptno, 10, 'Y', 20, 'P', 'N') in ('P','N');


--Identify the Slow SQLs

SELECT *

FROM (

  SELECT sql_id, executions, elapsed_time,executions avg_time, sql_text

  FROM v$sql

  WHERE elapsed_time

  /*executions*/ IS NOT NULL

  ORDER BY avg_time DESC

)

WHERE ROWNUM <= 10;


--Check if the Package is Still Running or Hung

SELECT s.sid, s.serial#, s.username, s.status, s.sql_id, s.event, s.wait_class, s.seconds_in_wait

FROM v$session s

WHERE s.username = 'ODI_SRC'

  AND s.status = 'ACTIVE';


--Check for Locks or Blocking Sessions

SELECT

    a.sid blocker_sid,

    b.sid blocked_sid,

    a.username blocker_user,

    b.username blocked_user,

    b.event

FROM v$session a, v$session b

WHERE a.sid IN (SELECT blocking_session FROM v$session WHERE blocking_session IS NOT NULL)

  AND b.blocking_session = a.sid;


--Check for Recent SQL/PLSQL Errors

SELECT *

FROM dba_errors

WHERE name = 'GET_EMP'

  AND owner = 'ODI_SRC';


--Check System Resource Usage

SELECT * FROM v$resource_limit

WHERE resource_name IN ('sessions', 'processes');


--Or

SELECT * FROM v$sysmetric_summary

WHERE metric_name LIKE '%CPU%' OR metric_name LIKE '%Memory%';


--Example: Materialized View

CREATE MATERIALIZED VIEW emp_mv

BUILD IMMEDIATE

REFRESH FAST ON COMMIT

AS

SELECT deptno, COUNT(*) emp_count

FROM emp

GROUP BY deptno;


--How to Check If a View Is Updatable?

SELECT view_name, updatable

FROM user_updatable_columns

WHERE view_name = 'EMP_VIEW';


--Index may be missing or not used due to function or implicit conversion

create index ixd_hiredate on emp(hiredate);


explain plan for

select * from emp where to_char(HIREDATE)='23-12-80';


select * from table(dbms_xplan.display);


--Declared a procedure in the package body and it is not declared in the package specification. Will that package run or not?

CREATE OR REPLACE PACKAGE my_pkg AS

  PROCEDURE proc_pub;

END my_pkg;



CREATE OR REPLACE PACKAGE BODY my_pkg AS


  -- Public procedure (declared in spec)

  PROCEDURE proc_pub IS

  BEGIN

    proc_priv; -- calling private proc

    DBMS_OUTPUT.PUT_LINE('Public procedure');

  END;


  -- Private procedure (not in spec)

  PROCEDURE proc_priv IS

  BEGIN

    DBMS_OUTPUT.PUT_LINE('Private procedure');

  END;


END my_pkg;


EXEC my_pkg.proc_pub;



drop PACKAGE my_pkg;


drop PACKAGE BODY my_pkg;


set serveroutput on;


--3rd highest salary

SELECT sal

FROM (

  SELECT DISTINCT sal

  FROM emp

  ORDER BY sal DESC

)

WHERE ROWNUM =3;


--get employees whose salary is more than the average salary of their own department:

SELECT empno, ename, deptno, sal

FROM emp e

WHERE sal > (

  SELECT AVG(sal)

  FROM emp

  WHERE deptno = e.deptno

);


--mutating table error

CREATE OR REPLACE TRIGGER trg_emp_update

AFTER UPDATE ON emp

--for each row -it cause mutating table error

declare

v_count number;

BEGIN

  -- Valid: statement-level can query emp

  select count(*) into v_count from emp;

  dbms_output.put_line(v_count);

  --INSERT INTO log_table SELECT * FROM emp WHERE deptno = 10;

END;


select * from emp;


update emp set sal=250000 where empno=8376;

Oracle SQL and PL/SQL Interview and Concept Notes - 02 July 2025 - 7

What is a Cursor and Its Types

In PL/SQL, a cursor is a pointer to the result set of a query. It allows row-by-row processing.

Types of Cursors:
1. Implicit Cursor – Automatically created for single-row queries.
2. Explicit Cursor – Developer-defined for multi-row queries.
3. Cursor FOR Loop – Simplified looping over query results.
4. Parameterized Cursor – Accepts input parameters.
5. REF Cursor – Dynamic pointer to query results.

Example of Explicit Cursor:
DECLARE
  CURSOR c_emp IS SELECT empno, ename FROM emp;
  v_empno emp.empno%TYPE;
  v_ename emp.ename%TYPE;
BEGIN
  OPEN c_emp;
  LOOP
    FETCH c_emp INTO v_empno, v_ename;
    EXIT WHEN c_emp%NOTFOUND;
    DBMS_OUTPUT.PUT_LINE(v_empno || ' ' || v_ename);
  END LOOP;
  CLOSE c_emp;
END;

Cursor Attributes

1. %FOUND – TRUE if last fetch/DML affected rows.
2. %NOTFOUND – TRUE if no rows fetched/affected.
3. %ROWCOUNT – Number of rows fetched/affected.
4. %ISOPEN – TRUE if explicit cursor is currently open.

Example:
UPDATE emp SET sal = sal + 100 WHERE deptno = 10;
IF SQL%FOUND THEN
  DBMS_OUTPUT.PUT_LINE('Rows updated: ' || SQL%ROWCOUNT);
ELSE
  DBMS_OUTPUT.PUT_LINE('No rows updated.');
END IF;

Mutating Table Error

Occurs when a row-level trigger tries to read/write from the same table it's modifying.

Error: ORA-04091

Solutions:
1. Use statement-level triggers.
2. Use compound triggers.
3. Use :NEW and :OLD values.
4. Use autonomous transaction procedures.

Example (Avoiding Mutating Error):
Use compound trigger with memory table to collect and process after statement.

Query for Employees Earning More Than Department Average

SELECT empno, ename, deptno, sal
FROM emp e
WHERE sal > (
  SELECT AVG(sal) FROM emp WHERE deptno = e.deptno
);

Types of Analytical Functions

1. Ranking: RANK(), DENSE_RANK(), ROW_NUMBER(), NTILE()
2. Aggregate: SUM(), AVG(), COUNT(), MIN(), MAX()
3. Value: LEAD(), LAG(), FIRST_VALUE(), LAST_VALUE()
4. Distribution: PERCENT_RANK(), CUME_DIST()
5. Statistical: STDDEV(), VARIANCE(), CORR(), COVAR_POP(), COVAR_SAMP()

DENSE_RANK() Function

DENSE_RANK() assigns rank to rows without skipping ranks for ties.

Example:
SELECT sal, DENSE_RANK() OVER (ORDER BY sal DESC) AS rnk FROM emp;

3rd Maximum Salary Query

Method using DENSE_RANK():
SELECT sal FROM (
  SELECT sal, DENSE_RANK() OVER (ORDER BY sal DESC) AS rnk
  FROM emp
) WHERE rnk = 3;

Maximum Salary Query

SELECT MAX(sal) AS max_salary FROM emp;

To fetch employee(s) with max salary:
SELECT empno, ename, sal
FROM emp
WHERE sal = (SELECT MAX(sal) FROM emp);

Constraints and Types

1. PRIMARY KEY – Unique and NOT NULL.
2. UNIQUE – No duplicate values.
3. NOT NULL – Must contain value.
4. CHECK – Validates condition.
5. FOREIGN KEY – Enforces relationship with another table.

Yellow Interface

"Yellow interface" refers to ODI 11g's old data integration interface, which had a yellow UI. In ODI 12c, it's replaced by Mappings.

Bulk Collect

Used to fetch multiple rows into collections in one go to improve performance.

Example:
SELECT empno BULK COLLECT INTO v_empnos FROM emp;

Types of Errors in PL/SQL

1. Syntax Errors – Compile-time issues.
2. Compilation Errors – Incorrect declarations.
3. Runtime Errors – At execution time.
4. Logical Errors – Wrong result, no crash.
5. Server Errors – ORA-xxxxx codes.
6. User-Defined Errors – Raised using RAISE or RAISE_APPLICATION_ERROR.

Click for full details in ChatGPT

ODI Interview Question and Answers 29 September 2025

  Q: What is the basic difference between ETL and ELT approach? A: ETL extracts and transforms data outside the DB before loading, while E...