A review of aggregation granularity mismatching the expected business output and how parent-child relationships inflate critical metrics.
SELECT user_id, SUM(amount) AS total_spent
FROM orders
INNER JOIN users ON orders.user_id = users.id
WHERE status = 'Active'
GROUP BY user_id;
-> Hash Aggregate (user_id)
-> Hash Join (orders.user_id = users.id)
-> Filter (users.status = 'Active')
-> Seq Scan on users
-> Seq Scan on orders
In database engineering, an aggregation granularity mismatch occurs when the level of detail in the grouping columns does not match the semantic level of the metrics we intend to calculate. For instance, developers frequently join a parent table, such as users or orders, with a child table containing multiple records, like order_items or user_sessions, and then perform a sum or count operation. Because the join duplicates the parent rows for each matching child row, the subsequent aggregation calculates values based on the expanded child grain rather than the parent grain. This leads to inflated financial metrics, incorrect user counts, and general confusion in downstream business intelligence platforms. To prevent this, query authors must establish the target granularity of the final result set before writing joins. They should use subqueries or Common Table Expressions (CTEs) to aggregate child data to the parent grain first, and only then perform the join. This isolates the aggregation scope and guarantees that each business entity is represented exactly once in the final calculation, keeping reports reliable and accurate.
Often in production data environments, developers default to simple joins without reviewing the row multiplicity. When duplicate keys exist or table joins do not represent direct dependencies, metrics like revenue and active user count become inflated.
Always verify the primary keys of joined datasets and execute aggregate checks before using nested layouts. Improperly scoped aggregation levels will distort downstream BI dashboard reports.
Discussion & Reviews
This could be your first comment
Be the first to share your thoughts on this aggregation case!
Leave a Comment