Bird
0
0

Consider the query:

medium📝 query result Q5 of 15
PostgreSQL - Subqueries in PostgreSQL
Consider the query:
SELECT t.user_id, t.total_orders FROM (SELECT user_id, COUNT(*) AS total_orders FROM orders GROUP BY user_id) AS t WHERE t.total_orders < 5;

What does this query return?
AUsers with fewer than 5 orders
BAll orders with user IDs
CUsers with exactly 5 orders
DSyntax error due to missing GROUP BY
Step-by-Step Solution
Solution:
  1. Step 1: Analyze the subquery

    The subquery counts orders per user and aliases as t.
  2. Step 2: Apply the WHERE filter

    The outer query selects users with total orders less than 5.
  3. Final Answer:

    Users with fewer than 5 orders -> Option A
  4. Quick Check:

    Subquery counts orders; outer filters count < 5 [OK]
Quick Trick: Subquery counts; outer query filters by count condition [OK]
Common Mistakes:
  • Confusing total orders with individual orders
  • Missing GROUP BY in subquery
  • Misinterpreting the WHERE clause

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes