CS FundamentalsHardAmazon · Microsoft MCQ pattern

Table Emp(id, name, dept, salary, mgr) rows: (1, 'Asha', 'HR', 50000, NULL), (2, 'Ravi', 'IT', 70000, 1), (3, 'Meena', 'IT', 70000, 2), (4, 'John', 'Sales', 40000, 1), (5, 'Kiran', 'IT', 90000, 2), (6, 'Dev', NULL, 45000, 4), (7, 'Lata', 'Sales', NULL, 4). What do the two queries return?

Table Emp(id, name, dept, salary, mgr) rows: (1, 'Asha', 'HR', 50000, NULL), (2, 'Ravi', 'IT', 70000, 1), (3, 'Meena', 'IT', 70000, 2), (4, 'John', 'Sales', 40000, 1), (5, 'Kiran', 'IT', 90000, 2), (6, 'Dev', NULL, 45000, 4), (7, 'Lata', 'Sales', NULL, 4). What do the two queries return?
-- Q1
SELECT salary FROM (
  SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS r
  FROM Emp WHERE salary IS NOT NULL) t
WHERE r = 3;
-- Q2
SELECT salary FROM (
  SELECT salary, ROW_NUMBER() OVER (ORDER BY salary DESC) AS r
  FROM Emp WHERE salary IS NOT NULL) t
WHERE r = 3;
  1. A. Q1: 45000, Q2: 70000
  2. B. Q1: 50000, Q2: 50000
  3. C. Q1: 50000, Q2: 70000
  4. D. Q1: 70000, Q2: 50000

Correct answer: C. Q1: 50000, Q2: 70000

Distinct salaries descending: 90000, 70000, 50000, so the 3rd highest distinct salary (DENSE_RANK = 3) is 50000. ROW_NUMBER numbers the rows 90000, 70000, 70000, …, so row 3 is the second 70000. Use DENSE_RANK for the 'nth highest salary' problem.

More DBMS and SQL questions

Exams that ask this topic