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.
Code
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
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What are the relations in play here?
- `events` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.