Bird
0
0

Given the table orders with columns order_id and amount, what will this query return?

medium📝 query result Q4 of 15
PostgreSQL - Window Functions in PostgreSQL
Given the table orders with columns order_id and amount, what will this query return?
SELECT order_id, amount, LAG(amount) OVER (ORDER BY order_id) AS prev_amount FROM orders;
AEach row shows the current amount and the amount from the next order_id
BThe query will cause a syntax error
CEach row shows only the current amount repeated twice
DEach row shows the current amount and the amount from the previous order_id
Step-by-Step Solution
Solution:
  1. Step 1: Understand LAG usage

    LAG(amount) OVER (ORDER BY order_id) returns the amount from the previous row ordered by order_id.
  2. Step 2: Analyze the output

    For each order_id, the query shows its amount and the amount from the previous order_id row. The first row's prev_amount will be NULL.
  3. Final Answer:

    Each row shows the current amount and the amount from the previous order_id -> Option D
  4. Quick Check:

    LAG returns previous row's value, so output matches Each row shows the current amount and the amount from the previous order_id [OK]
Quick Trick: LAG returns previous row's value in ORDER BY sequence [OK]
Common Mistakes:
  • Confusing LAG with LEAD
  • Expecting next row value
  • Thinking query errors
  • Ignoring NULL for first row

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes