Bird
0
0

Given the table students with columns class and name, what is the output of this query?

medium📝 query result Q13 of 15
PostgreSQL - Aggregate Functions and GROUP BY
Given the table students with columns class and name, what is the output of this query?
SELECT class, ARRAY_AGG(name ORDER BY name) FROM students GROUP BY class ORDER BY class;
A[{class: '1A', array_agg: ['Alice']}, {class: '2B', array_agg: ['Charlie', 'David', 'Bob']}]
B[{class: '1A', array_agg: ['Bob', 'Alice']}, {class: '2B', array_agg: ['David', 'Charlie']}]
C[{class: '1A', array_agg: ['Alice', 'Charlie']}, {class: '2B', array_agg: ['Bob', 'David']}]
D[{class: '1A', array_agg: ['Alice', 'Bob']}, {class: '2B', array_agg: ['Charlie', 'David']}]
Step-by-Step Solution
Solution:
  1. Step 1: Understand GROUP BY and ARRAY_AGG with ORDER BY

    The query groups rows by class and collects names into arrays sorted alphabetically.
  2. Step 2: Analyze the ordering inside ARRAY_AGG

    Names inside each class array are sorted ascending, so 'Alice' comes before 'Bob' in '1A', and 'Charlie' before 'David' in '2B'.
  3. Final Answer:

    [{class: '1A', array_agg: ['Alice', 'Bob']}, {class: '2B', array_agg: ['Charlie', 'David']}] -> Option D
  4. Quick Check:

    ARRAY_AGG with ORDER BY sorts array elements [OK]
Quick Trick: ARRAY_AGG(... ORDER BY ...) sorts array elements [OK]
Common Mistakes:
  • Ignoring ORDER BY inside ARRAY_AGG
  • Mixing names between groups
  • Assuming ARRAY_AGG sorts groups, not elements

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PostgreSQL Quizzes