Bird
0
0

You want to compare each employee's salary with the salary two rows before them ordered by hire_date. Which query correctly achieves this?

hard📝 Application Q8 of 15
PostgreSQL - Window Functions in PostgreSQL
You want to compare each employee's salary with the salary two rows before them ordered by hire_date. Which query correctly achieves this?
ASELECT employee_id, salary, LAG(salary, 2) OVER (ORDER BY hire_date) AS salary_two_before FROM employees;
BSELECT employee_id, salary, LEAD(salary, 2) OVER (ORDER BY hire_date) AS salary_two_before FROM employees;
CSELECT employee_id, salary, LAG(salary) OVER (PARTITION BY hire_date) AS salary_two_before FROM employees;
DSELECT employee_id, salary, LAG(salary, 2) FROM employees ORDER BY hire_date;
Step-by-Step Solution
Solution:
  1. Step 1: Identify correct function and offset

    LAG with offset 2 gets value two rows before in the order specified.
  2. Step 2: Check query correctness

    SELECT employee_id, salary, LAG(salary, 2) OVER (ORDER BY hire_date) AS salary_two_before FROM employees; uses LAG(salary, 2) OVER (ORDER BY hire_date), which is correct. SELECT employee_id, salary, LEAD(salary, 2) OVER (ORDER BY hire_date) AS salary_two_before FROM employees; uses LEAD (wrong direction). SELECT employee_id, salary, LAG(salary) OVER (PARTITION BY hire_date) AS salary_two_before FROM employees; partitions by hire_date (likely one row per partition). SELECT employee_id, salary, LAG(salary, 2) FROM employees ORDER BY hire_date; misses OVER clause.
  3. Final Answer:

    SELECT employee_id, salary, LAG(salary, 2) OVER (ORDER BY hire_date) AS salary_two_before FROM employees; -> Option A
  4. Quick Check:

    LAG with offset 2 and ORDER BY hire_date is correct [OK]
Quick Trick: Use LAG with offset and ORDER BY for previous rows comparison [OK]
Common Mistakes:
  • Using LEAD instead of LAG
  • Missing OVER clause
  • Incorrect PARTITION BY usage
  • Omitting offset argument

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes