Joins and Aggregations: SQL Patterns for Data Analysis

Examples of SQL joins, GROUP BY, HAVING, and window functions, with checks for NULLs, unmatched keys, and filter placement.

published: reading time: 19 min read author: Geek Workbench updated: November 20, 2026
Quick Summary

This guide covers common SQL joins, GROUP BY, HAVING, and window functions. It shows how one-to-many matches affect row counts, how NULLs appear in outer joins, and when optional checks for unmatched keys are useful.

Joins and Aggregations: SQL Patterns for Data Analysis

Joins combine rows from related tables. Aggregations summarize those rows, so the join affects what reaches the summary. This guide uses customer and order examples to explain common join types, GROUP BY, HAVING, and window functions. It also shows how NULLs appear in outer joins and how to check assumptions about keys.

Understanding Joins

A join combines rows from two or more tables based on a condition. Choose a join type based on which matching and unmatched rows the query should keep.

flowchart LR
    subgraph A["Table A (customers)"]
        A1["id=1 Alice"]
        A2["id=2 Bob"]
        A3["id=3 Carol"]
    end
    subgraph B["Table B (orders)"]
        B1["id=1 Alice → order 101"]
        B2["id=1 Alice → order 102"]
        B3["id=4 Dave (no match)"]
    end
    subgraph IJ["INNER JOIN"]
        IJ1["Alice order 101"]
        IJ2["Alice order 102"]
    end
    subgraph LJ["LEFT JOIN"]
        LJ1["Alice order 101"]
        LJ2["Alice order 102"]
        LJ3["Bob → NULL"]
        LJ4["Carol → NULL"]
    end
    subgraph OJ["FULL OUTER JOIN"]
        OJ1["Alice order 101"]
        OJ2["Alice order 102"]
        OJ3["Bob → NULL"]
        OJ4["Carol → NULL"]
        OJ5["NULL → Dave"]
    end
    A1 --> IJ1
    B1 --> IJ1
    A1 --> LJ1
    B1 --> LJ1
    A2 --> LJ3
    A3 --> LJ4
    A1 --> OJ1
    B1 --> OJ1
    A2 --> OJ3
    A3 --> OJ4
    B3 --> OJ5

Inner Join

An inner join returns pairs of rows that satisfy the join condition. Customers without orders and orders without a matching customer are excluded. That is expected when the question asks only for matched records.

SELECT
    c.customer_id,
    c.customer_name,
    o.order_id,
    o.total_amount
FROM customers c
INNER JOIN orders o ON c.customer_id = o.customer_id;

Missing matches indicate a data-quality issue only when the data contract says they should exist. For example, if every non-null orders.customer_id must refer to a customers.customer_id, an unenforced foreign key or an upstream data problem could violate that rule. If the query intentionally selects only orders with known customers, excluding other rows is the requested result.

Optional Join Validation

When you expect every non-null order key to match exactly one customer, these checks can help verify that assumption. They are optional; they are not required before every join. The counts should match only if every order has a non-null, matching key and customers.customer_id is unique. Null or unmatched order keys make the joined count smaller; duplicate customer keys can make it larger.

SELECT COUNT(*) AS order_rows
FROM orders;

SELECT COUNT(*) AS matched_order_rows
FROM orders AS o
INNER JOIN customers AS c ON c.customer_id = o.customer_id;

Check null foreign keys separately:

SELECT COUNT(*) AS orders_without_customer_id
FROM orders
WHERE customer_id IS NULL;

An anti-join finds non-null order keys that have no customer row:

SELECT o.customer_id, COUNT(*) AS unmatched_orders
FROM orders AS o
LEFT JOIN customers AS c ON c.customer_id = o.customer_id
WHERE o.customer_id IS NOT NULL
  AND c.customer_id IS NULL
GROUP BY o.customer_id;

Left Join

A left join returns every row from the left table. When no right-side row matches, the selected right-side columns are NULL.

SELECT
    c.customer_id,
    c.customer_name,
    o.order_id,
    o.total_amount
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id;

This is useful when the report needs every customer, including customers with no orders. A filter on a right-side column can change that result depending on where it appears.

Suppose Alice has one paid order and one pending order, while Bob has no orders. To keep every customer and show only paid orders, put the status condition in the join condition:

SELECT c.customer_id, c.customer_name, o.order_id AS paid_order_id
FROM customers c
LEFT JOIN orders o
  ON c.customer_id = o.customer_id
 AND o.status = 'PAID';

The result is:

customer_id customer_name paid_order_id
1 Alice 101
2 Bob NULL

If the status predicate is in WHERE instead, Bob’s NULL-extended row does not pass the predicate and is removed:

SELECT c.customer_id, c.customer_name, o.order_id
FROM customers c
LEFT JOIN orders o ON c.customer_id = o.customer_id
WHERE o.status = 'PAID';

Use WHERE when the intended result excludes customers without a paid order. Use the condition in ON when those customers must remain in the output. This distinction applies to filters on the nullable side of an outer join; it does not generally apply the same way to inner joins.

Right Join

A right join preserves every row from the right table and fills the left-side columns with NULL where no match exists. It is valid SQL. Teams often prefer a left join with the table order reversed for consistency:

SELECT
    c.customer_id,
    c.customer_name,
    o.order_id,
    o.total_amount
FROM orders o
LEFT JOIN customers c ON o.customer_id = c.customer_id;

Full Outer Join

A full outer join returns all rows from both tables, with NULLs where there is no match. The practical use case is data quality checks: finding records that exist in one table but not the other. The danger is that NULLs on both sides complicate downstream aggregation.

SELECT
    c.customer_id,
    c.customer_name,
    o.order_id,
    o.total_amount
FROM customers c
FULL OUTER JOIN orders o ON c.customer_id = o.customer_id;

This includes matched rows and rows found on only one side. Aggregates such as SUM ignore NULL inputs; they do not turn a missing value into zero. Use COALESCE only when the business meaning of a missing amount is actually zero.

Cross Join

A cross join produces every pair of rows from its two inputs. The output size is the product of their row counts: 100 customers and 50 products produce 5,000 rows; 10,000 customers and 1 million products produce 10 billion.

SELECT
    c.customer_name,
    p.product_name
FROM customers c
CROSS JOIN products p;

Cross joins are useful when a result needs every combination, such as one row per customer per month before sales are added. They can also help generate test data. Before running one on large inputs, estimate the output as the row count of the first input multiplied by the row count of the second; inspect table statistics or use a representative sample when an exact count would be costly.

SELECT
    o.order_id,
    c.customer_name,
    p.product_name,
    oi.quantity,
    oi.unit_price
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
JOIN order_items oi ON o.order_id = oi.order_id
JOIN products p ON oi.product_id = p.product_id
WHERE o.order_date >= '2026-01-01';

This query associates orders with customers, order items, and products. The number of output rows depends on the relationships among those keys. The optimizer may push the date filter earlier when that preserves the query’s meaning; the order of the JOIN clauses does not force that plan. Use EXPLAIN (and, where appropriate, EXPLAIN ANALYZE) to inspect the plan on your database.

Aliases for Readability

Long table names get tedious. Use aliases. The other reason aliases matter is avoiding ambiguous references when the same table is joined multiple times. A query that joins customers to themselves to find parent-child relationships needs two different aliases for the same table.

SELECT
    o.order_id,
    c.customer_name,
    p.product_name
FROM orders o
JOIN customers c ON o.customer_id = c.customer_id
JOIN products p ON o.product_id = p.product_id

Aliases like o, c, and p are short but meaningful once you are familiar with the schema. In a four-table join, the aliases also make it obvious which table each column comes from without reading the FROM clause. The common failure is using the same alias for two different tables by mistake, which produces a syntax error that is usually caught. The worse failure is using no aliases with long table names, then accidentally using the wrong table’s column and getting silently wrong results.

Understanding Aggregations

Aggregations summarize data across multiple rows. They transform rows into summary values.

Basic Aggregations

SELECT
    COUNT(*) AS total_orders,
    SUM(total_amount) AS total_revenue,
    AVG(total_amount) AS average_order_value,
    MIN(order_date) AS first_order_date,
    MAX(order_date) AS last_order_date
FROM orders;

These scalar aggregations return a single row with summary statistics. COUNT(*) counts rows, while COUNT(column) counts only non-NULL values in that column. SUM and AVG also ignore NULL inputs. That does not mean a missing amount is known to be zero; decide what NULL means in the data before presenting a total.

GROUP BY

GROUP BY creates one result row per group. Database engines differ in which non-aggregated expressions they allow in the SELECT list, so follow the rules for the engine you use.

SELECT
    customer_id,
    COUNT(*) AS order_count,
    SUM(total_amount) AS lifetime_value
FROM orders
GROUP BY customer_id;

One row per customer, with aggregated order statistics. If a customer has no orders, they do not appear in the result because GROUP BY customer_id groups only rows that exist in the orders table. To include customers with zero orders, you need a left join from customers to orders first.

Multiple Columns in GROUP BY

Each unique combination of the grouped columns produces one group. Grouping rules for selected expressions vary across database engines, so check the syntax supported by your database.

SELECT
    customer_id,
    DATE_TRUNC('month', order_date) AS order_month,
    COUNT(*) AS order_count
FROM orders
GROUP BY customer_id, DATE_TRUNC('month', order_date)
ORDER BY customer_id, order_month;

This gives you monthly order counts per customer. The DATE_TRUNC truncates the timestamp to the month, so all orders in the same month group together. The ORDER BY is separate from the GROUP BY and controls the sort order of the result, not the grouping itself. A common mistake is thinking ORDER BY customer_id, order_month will make all rows for the same customer appear together; that is what GROUP BY does. The ORDER BY is only for the presentation order of the grouped rows.

Filtering Aggregates with HAVING

WHERE filters rows before aggregation. HAVING filters groups after aggregation.

SELECT
    customer_id,
    SUM(total_amount) AS lifetime_value
FROM orders
GROUP BY customer_id
HAVING SUM(total_amount) > 10000;

This finds high-value customers. Only customers with more than $10,000 in total orders appear.

Combining Joins and Aggregations

A common analytical query joins related tables and then aggregates the resulting rows.

SELECT
    c.customer_name,
    c.customer_region,
    SUM(o.total_amount) AS total_revenue,
    COUNT(o.order_id) AS order_count,
    AVG(o.total_amount) AS avg_order_value
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id
WHERE o.order_date >= '2026-01-01'
GROUP BY c.customer_name, c.customer_region
ORDER BY total_revenue DESC
LIMIT 20;

This returns the top 20 customers by revenue, with their region and order statistics.

Window Functions

Window functions perform calculations across a set of rows related to the current row. Unlike aggregate functions, they do not collapse rows.

Running Totals

SELECT
    order_date,
    daily_revenue,
    SUM(daily_revenue) OVER (
        ORDER BY order_date
        ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
    ) AS running_total
FROM daily_sales;

The running total sums all revenue from the beginning through the current row. The window frame ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW is what makes it a running total rather than a grand total. UNBOUNDED PRECEDING means include all rows from the start of the partition, and CURRENT ROW means stop at the current row. Without this frame specification, SUM() OVER() computes the sum of all rows in the partition, which is the same as a grand total.

Rank and Row Number

SELECT
    customer_name,
    lifetime_value,
    ROW_NUMBER() OVER (ORDER BY lifetime_value DESC) AS row_num,
    RANK() OVER (ORDER BY lifetime_value DESC) AS rank,
    DENSE_RANK() OVER (ORDER BY lifetime_value DESC) AS dense_rank
FROM customer_lifetime_values;

The difference between these three is what happens when two rows have the same value:

  • ROW_NUMBER assigns sequential numbers regardless of ties. If two customers are tied at $10,000, one gets row_num 1 and the other gets row_num 2, but which one gets which is arbitrary.
  • RANK assigns the same rank to ties, then skips the next rank. If two customers tie at rank 1, the next customer gets rank 3.
  • DENSE_RANK assigns the same rank to ties without skipping. If two customers tie at rank 1, the next customer gets rank 2.

Use ROW_NUMBER when you need a unique, stable ordering for pagination or deduplication. Use RANK when you are building a leaderboard where ties mean the next rank is skipped. Use DENSE_RANK when ties should not affect the ranking of others, such as in qualification thresholds where the top 10 by score make a cutoff.

Partition By

PARTITION BY restarts the window for each group. Without PARTITION BY, the window function operates over the entire result set. With PARTITION BY, it resets for each group.

SELECT
    customer_name,
    order_month,
    monthly_revenue,
    SUM(monthly_revenue) OVER (
        PARTITION BY customer_name
        ORDER BY order_month
    ) AS cumulative_revenue_per_customer
FROM customer_monthly_revenue;

The running total restarts for each customer. This is the key difference from a simple running total: the PARTITION BY customer_name splits the data into one partition per customer, and the SUM() OVER() and ORDER BY order_month apply independently within each partition. Without PARTITION BY, the running total would span all customers and all months, producing a single cumulative sum across the entire table.

Common Analytical Patterns

Year-over-Year Comparison

SELECT
    DATE_TRUNC('month', order_date) AS month,
    SUM(total_amount) AS current_month_revenue,
    LAG(SUM(total_amount)) OVER (ORDER BY DATE_TRUNC('month', order_date)) AS previous_month_revenue,
    SUM(total_amount) - LAG(SUM(total_amount)) OVER (ORDER BY DATE_TRUNC('month', order_date)) AS month_over_month_change
FROM orders
GROUP BY DATE_TRUNC('month', order_date)
ORDER BY month;

Percentage of Total

SELECT
    product_category,
    SUM(revenue) AS category_revenue,
    SUM(SUM(revenue)) OVER () AS total_revenue,
    SUM(revenue) * 100.0 / SUM(SUM(revenue)) OVER () AS percent_of_total
FROM product_sales
GROUP BY product_category
ORDER BY percent_of_total DESC;

The nested SUM aggregate computes the total, and the window function makes it available to every row.

Moving Averages

SELECT
    order_date,
    daily_revenue,
    AVG(daily_revenue) OVER (
        ORDER BY order_date
        ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
    ) AS seven_day_moving_average
FROM daily_sales;

This computes a 7-day moving average, including the current day and the 6 preceding days.

Join Performance Considerations

Joins can be expensive. A few principles help keep queries fast.

Indexes and Join Performance

Indexes can help when a query filters or joins on selective keys, but a join does not require indexes on both sides. The planner may choose a nested-loop, hash, or merge join depending on table sizes, indexes, statistics, and the query. A sequential scan can be the right plan for a large share of a table.

Use EXPLAIN to inspect the plan and benchmark representative data before adding indexes. In PostgreSQL, creating a foreign key does not automatically create an index on the referencing column.

Filter Placement

For inner joins, the optimizer can often push a WHERE filter closer to the table it applies to when the result stays the same. Wrapping a filtered table in a subquery does not guarantee that the database will materialize it before the join.

For outer joins, moving a filter between ON and WHERE can change which unmatched rows appear. The left-join example above shows the difference. Put each condition where it matches the result you want, then inspect the query plan if performance is a concern.

Cross Join Size

A cross join returns every possible pair of rows. That can be intentional, but check the expected output size first: multiply the input row counts or estimate them from table statistics. An omitted join condition can produce a Cartesian product, so review the predicates when a query returns far more rows than expected.

Common Pitfalls

Ambiguous Column Names

When two tables have columns with the same name, qualify them with table aliases. The error this produces depends on the database mode. In strict SQL modes, the query fails with an ambiguous column error. In permissive modes, it silently picks one, which is worse because the query runs but returns wrong results.

-- WRONG if both tables have customer_id
SELECT customer_id FROM customers c JOIN orders o ON c.customer_id = o.customer_id;

-- RIGHT: specify which table
SELECT c.customer_id FROM customers c JOIN orders o ON c.customer_id = o.customer_id;

Qualifying columns with table aliases makes larger queries easier to read and helps avoid ambiguity if another joined table has a column with the same name.

NULL in Join Conditions

A comparison such as NULL = NULL does not evaluate to TRUE in SQL, so NULL join keys do not match with an ordinary equality condition. With an inner join, rows with a NULL key are excluded; with an outer join, unmatched rows can remain with NULLs on the other side.

Whether that exclusion is a problem depends on the data contract. If NULL means that a relationship is not assigned yet, dropping the row may be intentional for a matched-only report. If every row is expected to have a key, measure null and unmatched keys with the optional checks in the inner-join section.

Do not replace NULLs with a shared placeholder unless that value has the intended meaning and cannot collide with a real key. Otherwise, unrelated rows may be made to match.

Aggregation Without GROUP BY

-- WRONG: will fail or return unexpected results
SELECT customer_name, COUNT(*) FROM orders;

-- RIGHT: include all non-aggregated columns in GROUP BY
SELECT customer_name, COUNT(*) FROM orders GROUP BY customer_name;

Modern SQL modes like ONLY_FULL_GROUP_BY reject queries where non-aggregated columns are not in GROUP BY.

When to Use Each Join Type

Join Type When to Use Key Risk
INNER JOIN Return only matching row pairs Excludes unmatched rows; validate only when the data contract requires matches
LEFT JOIN Keep every left-side row and add right-side data when it matches A right-side WHERE filter can remove NULL-extended rows
RIGHT JOIN Keep every right-side row Can be harder to scan if the team normally writes left joins
FULL OUTER JOIN Keep matched and unmatched rows from both sides NULLs need interpretation before aggregation
CROSS JOIN Generate all combinations, such as a reporting grid Row count is the product of both input counts
SELF JOIN Compare or relate rows within one table Aliases and predicates need to distinguish the two row roles

SQL Observability Hooks

Track these metrics to diagnose query performance issues:

-- Identify large scans driving slow joins
SELECT
    schemaname,
    tablename,
    seq_scan,
    seq_tup_read,
    idx_scan,
    idx_tup_fetch,
    n_tup_ins,
    n_tup_upd,
    n_tup_del
FROM pg_stat_user_tables
WHERE seq_scan > 0
ORDER BY seq_tup_read DESC
LIMIT 20;

-- Review scan counts alongside indexes defined for each table; this does not identify foreign keys by itself
SELECT
    t.tablename,
    t.seq_scan,
    i.indexname,
    i.indexdef
FROM pg_stat_user_tables t
LEFT JOIN pg_indexes i ON t.schemaname = i.schemaname
    AND t.tablename = i.tablename
WHERE t.seq_scan > 1000
ORDER BY t.seq_scan DESC;

For queries that matter to the workload, record the tables involved, output row counts, and execution time. Investigate unexpectedly large results, high scan counts, and NULL or unmatched keys when the data contract requires matches.

SQL Production Failure Scenarios

Unexpected Cartesian product

Joining 10,000 customers to 100,000 orders without a join condition can produce one billion row pairs before later filtering. The actual runtime and storage cost depend on the database, data, and execution plan. If a query returns far more rows than expected, check the join predicates and review the plan before rerunning it on production-sized data.

Mitigation: Use explicit join conditions for related tables. Estimate output cardinality and inspect the plan with EXPLAIN; use EXPLAIN ANALYZE only when executing the query is safe for the target workload.

Unmatched or NULL join keys

An inner join excludes rows whose keys are NULL or have no matching row. That is expected for a report that asks only for matched records. It is a data-quality issue only when the data contract requires a match and the source violates that rule.

Mitigation: Check the contract first. If every non-null orders.customer_id should identify a customer, compare the order count with the matched count and use the anti-join check in the optional validation section. Track NULL foreign keys separately. Avoid normalizing all missing keys to a shared string; that can create matches that do not exist in the source data.

Join plan scans a large table

A sequential scan is not automatically a problem. For some joins, the planner may choose a hash join over sequential scans; for others, an index can help. The choice depends on selectivity, table size, statistics, and the query.

Mitigation: Inspect the plan and measure with representative data before adding an index. In PostgreSQL, EXPLAIN ANALYZE executes the query, so use it only when that workload is safe to run.

FULL OUTER JOIN and downstream totals

A full outer join can return rows with no match on one side. Aggregate functions such as SUM ignore NULL inputs, but whether the resulting total is incomplete depends on what the missing value means. If a missing amount means zero in the business model, COALESCE may be appropriate; otherwise, keep unmatched rows visible and report them separately rather than assigning a value.

Mitigation: Inspect unmatched rows and confirm the metric’s definition before replacing NULL with zero. Compare matched and unmatched counts as part of the query review.

SQL Joins and Aggregations Quick Recap

  • INNER JOIN returns matching row pairs; whether excluded rows are a problem depends on the data contract.
  • LEFT JOIN preserves left-side rows. A filter on right-side columns in WHERE can remove rows whose right-side values are NULL.
  • RIGHT JOIN is valid; reverse the table order and use LEFT JOIN when that reads more clearly.
  • FULL OUTER JOIN keeps unmatched rows from both inputs; interpret NULLs before aggregating.
  • CROSS JOIN returns every possible pair, so estimate the output size first.
  • GROUP BY creates groups; WHERE filters rows and HAVING filters groups.
  • Window functions calculate values across related rows without collapsing them.
  • Use row counts and anti-joins as optional checks when key relationships are expected.

For data modeling, see Kimball Dimensional Modeling and Slowly Changing Dimensions. For a more detailed discussion of relationship cardinality, continue to Understanding SQL JOINs and Database Relationships.

The examples here use common SQL syntax, but features such as FULL OUTER JOIN and date functions vary by database. Check your database’s documentation and inspect its query plan when behavior or performance matters.

Category

Related Posts

DuckDB: The SQLite for Analytical Workloads

Explore DuckDB, the in-process analytical database that runs anywhere, handles columnar storage efficiently, and brings analytics to where your data lives.

#data-engineering #duckdb #olap

Data Warehousing

Learn warehouse modeling concepts: OLTP and OLAP, star and snowflake schemas, fact and dimension tables, and slowly changing dimensions.

#database #data-warehouse #olap

Data Vault Modeling: Hubs, Links, Satellites, and Trade-offs

Learn how Data Vault hubs, links, and satellites organize integrated warehouse history, where deterministic hash keys fit, and when a simpler dimensional model is a better choice.

#data-engineering #data-modeling #data-vault