GROUPING SETS in Group Data helps you write SQL that is easier to test, review, and operate at scale.
Introduction to GROUPING SETS
Use GROUPING SETS to aggregate data into metrics for dashboards and analytics.
Commonly paired with: SELECT, FROM, ORDER BY, GROUP BY.
Practical examples with GROUPING SETS in PostgreSQL
Reference pattern: start from canonical syntax and keep it explicit.
SELECT region, channel, SUM(total_amount)
FROM sales
GROUP BY GROUPING SETS ((region), (channel), (region, channel));
Production-style scenario: apply the same concept to realistic application data.
SELECT
o.order_id,
o.total_amount,
o.placed_at
FROM orders o
WHERE o.placed_at >= now() - interval '30 days'
ORDER BY o.placed_at DESC
LIMIT 50;
Additional example: use a variation to validate behavior and edge cases.
SELECT date_trunc('month', placed_at) AS month,
SUM(total_amount) AS revenue
FROM orders
GROUP BY 1
ORDER BY 1;
Production tips
- Prefer explicit column lists and deterministic ordering when results feed APIs or batch jobs.
- Validate plans with
EXPLAINbefore adding indexes, then re-check after schema changes. - Keep DDL, data backfills, and cleanups in transactions when possible to avoid partial state.
- Use isolated environments for risky changes so query tuning and schema experiments stay safe.
Vela workflow tip
Test this pattern in an isolated branch database, share the result with your team, and promote only after query plans and row counts look correct.
Reference: PostgreSQL official documentation.