Skip to content
Visual explainer 8h to learn 6 steps

SQL: joins, grouping, subqueries, window functions

Answer real questions from a schema with SQL.

By Invicly Tech, , in Backend Java Development. About 12 minutes to read.

Topic 12 of 29

In short

SQL is how you ask a relational database questions. Joins combine tables, GROUP BY summarises rows, and window functions rank or total rows without collapsing them.

Explained simply

A relational database stores data in tables, like spreadsheets with strict columns. Each row is one thing: one customer, one order, one product. SQL (Structured Query Language) is the language you use to ask questions about those tables.

The core of SQL is SELECT. You say which columns you want, from which table, and which rows to keep. SELECT name FROM customers WHERE city = 'Pune' reads almost like English. You describe the result you want, and the database works out how to get it fast.

Real questions usually need several tables. Orders live in one table and customers in another, linked by a customer id. A JOIN puts matching rows side by side so you can ask things like: which customers spent the most last month?

Then you summarise. GROUP BY turns many rows into one row per group, such as one row per city with a total. Window functions go further: they can rank or total rows while still keeping every row. With these tools you can answer most business questions without writing any Java at all.

Press Play on a diagram to walk through it one step at a time.

FlowLogical order a SELECT runs in
  1. 1
    FROM and JOIN

    Build the combined set of rows

  2. 2
    WHERE

    Filter individual rows

  3. 3
    GROUP BY

    Collapse rows into groups

  4. 4
    HAVING

    Filter whole groups by aggregates

  5. 5
    SELECT

    Compute columns and window functions

  6. 6
    ORDER BY

    Sort the result

  7. 7
    LIMIT

    Keep the first N rows

CompareINNER JOIN vs LEFT JOIN
INNER JOIN
  • Only rows with a match in both
  • Unmatched rows disappear
  • Use when the relation must exist
LEFT JOIN
  • All rows from the left table
  • Right side is NULL when no match
  • Use to find missing data
FlowWriting a query step by step
  1. 1
    Restate the question

    What does one result row represent?

  2. 2
    Find the tables

    Which tables hold the facts you need?

  3. 3
    Join and check counts

    Run SELECT COUNT(*) after each join

  4. 4
    Filter rows

    WHERE before any grouping

  5. 5
    Group or window

    Summarise, rank or compare rows

  6. 6
    Sanity-check

    Test with a customer you know by hand

In depth

Joins and how they multiply rows

A join pairs every row on the left with every row on the right that meets the ON condition. If a customer has three orders, that customer appears three times in the result. This is expected, but it surprises people when they then SUM a column from the customer side and get a number three times too big. Aggregate at the right level, or aggregate in a subquery before joining.

LEFT JOIN keeps every left row and fills the right side with NULL when there is no match. That makes it the tool for finding missing data: LEFT JOIN orders and keep rows WHERE o.id IS NULL to find customers with no orders. This pattern is called an anti-join; NOT EXISTS does the same and is often clearer. A self-join joins a table to itself, for example employees to their managers.

MapJoin types at a glance
JOIN
  • INNER JOIN
    • Only matching pairs
    • The default for plain JOIN
  • LEFT JOIN
    • All left rows
    • NULLs where no match
  • FULL OUTER JOIN
    • All rows from both sides
    • Useful for reconciling two lists
  • CROSS JOIN
    • Every combination
    • Rows multiply: n times m
  • Self join
    • Table joined to itself
    • employees e JOIN employees m

NULL is not a value

NULL means unknown or missing, and it follows its own logic. Any comparison with NULL, even NULL = NULL, gives unknown, and WHERE keeps only rows where the condition is true. So WHERE phone = NULL never matches anything; write WHERE phone IS NULL.

This causes real bugs. COUNT(*) counts rows, but COUNT(phone) counts only rows where phone is not NULL. AVG ignores NULLs instead of treating them as zero. The nastiest trap: WHERE id NOT IN (SELECT manager_id FROM employees) returns no rows at all if any manager_id is NULL, because the database cannot be sure the id is not equal to that unknown value. Use NOT EXISTS instead, which behaves as you expect.

  • COALESCE(phone, 'none') replaces NULL with a default
  • a IS DISTINCT FROM b treats NULLs as comparable (PostgreSQL)
  • NOT IN plus a NULL in the list returns nothing

Grouping, HAVING and conditional counts

With GROUP BY, every column in SELECT must either be in the GROUP BY list or be inside an aggregate like COUNT, SUM, AVG, MIN or MAX. Otherwise the database would not know which of the many row values to show. PostgreSQL relaxes this a little: if you group by a table's primary key, you may select its other columns.

Often you want several counts in one pass, such as paid and refunded orders per day. PostgreSQL supports a FILTER clause: COUNT(*) FILTER (WHERE status = 'paid'). The portable version is SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END). Both avoid running several separate queries. Use HAVING only for conditions on aggregates; plain row filters belong in WHERE, where they reduce the work before grouping.

  • date_trunc('month', created_at) groups by month in PostgreSQL
  • GROUP BY 1, 2 groups by the first and second selected columns
  • ORDER BY the aggregate: ORDER BY SUM(total) DESC

Subqueries and CTEs

A subquery is a query inside another query. A scalar subquery returns one value, as in WHERE total > (SELECT AVG(total) FROM orders). IN and EXISTS test membership. A correlated subquery refers to the outer row, like EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id), and conceptually runs once per outer row, though the planner often turns it into a join.

A CTE (common table expression) gives a subquery a name with WITH, so a long query reads as steps. Since PostgreSQL 12, simple CTEs are inlined into the main query and optimised like subqueries; write AS MATERIALIZED to force one to be computed once. WITH RECURSIVE walks hierarchies such as category trees or org charts by repeatedly joining a table to the rows found so far.

Window functions: rank, compare and run totals

A window function computes a value across a set of related rows, called the window, without collapsing them. OVER (PARTITION BY dept ORDER BY salary DESC) means: restart for each department, ordered by salary. ROW_NUMBER, RANK and DENSE_RANK differ only on ties, as the diagram shows. LAG(total) and LEAD(total) read the previous or next row's value, which makes month-over-month change easy. SUM(total) OVER (ORDER BY day) gives a running total.

Window functions run after WHERE, GROUP BY and HAVING, so you cannot filter on them in the same WHERE clause. To keep only the top row per group, compute ROW_NUMBER in a CTE or subquery and filter on it outside. PostgreSQL also offers DISTINCT ON for the simple top-one-per-group case.

CompareRanking salaries 900, 800, 800, 700
ROW_NUMBER()
  • 1, 2, 3, 4
  • Always unique
  • Ties broken arbitrarily
  • Best for top N per group
RANK()
  • 1, 2, 2, 4
  • Ties share a rank
  • Leaves a gap after ties
  • Like sports rankings
DENSE_RANK()
  • 1, 2, 2, 3
  • Ties share a rank
  • No gaps
  • Good for distinct levels

Learn it in 6 short steps

About 1h 20m each. Track them with a timer in your plan.

  1. 1
    Write SELECT queries with filters and sorting~1h 20m
  2. 2
    Combine tables with inner and outer joins~1h 20m
  3. 3
    Aggregate with GROUP BY and HAVING~1h 20m
  4. 4
    Use subqueries and CTEs~1h 20m
  5. 5
    Rank rows with window functions~1h 20m
  6. 6
    Practise 20 queries on a sample schema~1h 20m

Key points

  • WHERE filters rows before grouping; HAVING filters groups after aggregation.
  • Because SELECT runs late, column aliases usually cannot be used in WHERE.
  • Window functions like RANK() OVER (PARTITION BY ...) keep every row.
  • CTEs (WITH ...) name intermediate results and make long queries readable.

Key terms

Tap a card to flip it. 0/5 known

Examples

sql
-- Departments with more than 5 staff
SELECT d.name, COUNT(*) AS staff, AVG(e.salary) AS avg_pay
FROM employees e
JOIN departments d ON d.id = e.dept_id
GROUP BY d.name
HAVING COUNT(*) > 5;

-- Rank employees by salary inside each department
SELECT name, dept_id, salary,
       RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS rnk
FROM employees;

Customers with their order counts, including zero

Marketing wants every customer and how many orders they placed, including people who never ordered. Step 1: an inner join would drop customers without orders, so use LEFT JOIN. Step 2: count o.id, not *, because for customers without orders the single joined row has NULL in o.id, so COUNT(o.id) gives 0 while COUNT(*) would wrongly give 1. Step 3: group by the customer's primary key. Step 4: a second query finds only the customers who never ordered, using NOT EXISTS.

sql
SELECT c.id, c.name, COUNT(o.id) AS orders
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.id, c.name
ORDER BY orders DESC;

-- Only customers who never ordered
SELECT c.id, c.name
FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);

Top 2 products per category

You need the two best-selling products in each category. Step 1: in a CTE, sum sales per product. Step 2: in a second CTE, number products inside each category by sales, highest first, with ROW_NUMBER. Step 3: filter rn <= 2 in the outer query, because a window function cannot be used in WHERE directly. If you want ties to share second place, swap ROW_NUMBER for DENSE_RANK.

sql
WITH sales AS (
  SELECT p.id, p.name, p.category_id, SUM(oi.quantity) AS sold
  FROM products p
  JOIN order_items oi ON oi.product_id = p.id
  GROUP BY p.id, p.name, p.category_id
),
ranked AS (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY category_id ORDER BY sold DESC) AS rn
  FROM sales
)
SELECT category_id, name, sold
FROM ranked
WHERE rn <= 2
ORDER BY category_id, rn;

Quick reference

  • Use IS NULL and IS NOT NULL; = NULL never matches
  • COUNT(*) counts rows; COUNT(col) skips NULLs
  • Prefer NOT EXISTS over NOT IN when the subquery can return NULL
  • Put conditions on the right table of a LEFT JOIN in ON, not in WHERE
  • COUNT(*) FILTER (WHERE status = 'paid') counts a subset (PostgreSQL)
  • Filter on a window function by wrapping it in a CTE or subquery
  • LAG(x) OVER (ORDER BY d) gives the previous row's value
  • UNION removes duplicates; UNION ALL keeps them and is faster

Common mistakes

  • Filtering a LEFT JOIN's right table in WHERE, which turns it into an INNER JOIN.
  • Comparing with = NULL instead of IS NULL.
  • Selecting non-grouped columns alongside aggregates.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A subquery used in NOT IN returns 3, 7 and NULL. What does WHERE id NOT IN (...) return?

Question 2

2Salaries are 900, 800, 800, 700. What does RANK() give the 700 row?

Question 3

3A table has 10 rows, and 4 of them have NULL in email. What does COUNT(email) return?

Question 4

4You LEFT JOIN orders and add WHERE o.status = 'paid'. Customers without orders disappear. Why?

Question 5

5Why does WHERE ROW_NUMBER() OVER (...) <= 3 fail?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    List the 10 largest orders from the last 30 days with the customer's name.

  2. Exercise 2medium

    Show revenue per month for this year, plus the number of paid and refunded orders per month.

  3. Exercise 3hard

    For each customer, show each order with a running total of their spending and the difference from their previous order.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is a JOIN faster than a subquery?
Often they perform the same, because the planner rewrites one into the other. Write the clearer version, then check with EXPLAIN if it is slow.
What is the difference between UNION and UNION ALL?
UNION removes duplicate rows from the combined result, which needs extra sorting or hashing. UNION ALL keeps every row and is faster when duplicates are impossible or fine.
Is SQL case-sensitive?
Keywords are not. In PostgreSQL, unquoted table and column names are folded to lower case, while string comparisons such as name = 'Ana' are case-sensitive; use ILIKE or lower() to ignore case.
Where can I practise SQL for free?
Install PostgreSQL locally or in Docker and load a sample database such as Pagila, or use interactive sites like SQLBolt and pgexercises.

Go deeper

ShareXLinkedInWhatsApp