array_agg Preserves Grouped Order

Collect group values in encounter order with array_agg and an inner ORDER BY, preserving sequence that plain aggregates lose.

SqlData Integrity

Code

snippet
WITH events (user_id, action, at) AS (
    VALUES
        (1, 'login', timestamp '2026-11-17 09:00'),
        (1, 'view',  timestamp '2026-11-17 09:05'),
        (2, 'login', timestamp '2026-11-17 10:00'),
        (1, 'logout', timestamp '2026-11-17 09:30')
)
SELECT
    user_id,
    array_agg(action ORDER BY at) AS actions,
    array_length(array_agg(action ORDER BY at), 1) AS action_count
FROM events
GROUP BY user_id
ORDER BY user_id;

-- actions 按 at 升序排列:login, view, logout 的原始顺序得以保留

How the snippet works

At its core this is a single SELECT statement against events.

Breaking the statements into their working parts: a CTE (WITH … AS) that names an intermediate result before the main query; a GROUP BY that collapses matching rows into one output row per group; an ORDER BY that fixes the output order.

Applying it

Run the statement against the events table.

Interactive Tools for This Topic

FAQ

What are the relations in play here?
`events` — referenced directly, no join needed.