image.png

You can now open VS Code, connect to PostgreSQL, and ask a table a question. You can filter products, count orders, and find customers with missing email addresses.

Then someone asks: “Who are our best customers?”

The customer names live in one table. Order dates and statuses live in another. The products and prices paid live somewhere else again. A filter on one table will only take you so far.

This is Part 2 of our three-part SQL series. We will use the database created in Part 1 to connect related records, calculate revenue, find repeat customers, and turn a longer query into steps you can read.

By the end, you will have a customer report that includes people who have never completed an order. You will also understand why a query can run successfully and still give you the wrong answer.

What We Will Learn in Part 2

Here is the toolkit we will use, with a business question for each feature. Some are functions, while others are SQL clauses or query structures; together, they let us build a complete report.

SQL feature What it helps you do Our example
INNER JOIN and ON Match related records across tables Attach a customer name to an order
LEFT JOIN and IS NULL Keep unmatched records and find missing relationships Find customers who have never ordered
SUM, COUNT, and COUNT(DISTINCT ...) Calculate totals and count at the right grain Measure revenue without counting order lines as orders
GROUP BY and HAVING Summarise rows, then filter the summaries Find customers with at least two completed orders
WITH / CTEs Split a longer query into named steps Calculate order totals before customer totals
COALESCE Supply a fallback for a missing value Display zero revenue for customers with no completed orders
CASE Assign labels using conditions Separate one-time buyers from repeat buyers
DATE_TRUNC and ::date Group dates into reporting periods and cast the result Build a monthly revenue report
Subqueries and AVG Compare a row with a calculated benchmark Find products priced above the catalogue average
LOWER and ILIKE Transform text and match patterns without case sensitivity Normalise email output and search customer names

We will also introduce fact tables, dimension tables, and grain using the four tables you already created. You will see how these ideas help you choose the right joins and avoid misleading totals.

Situation

Imagine the shop owner sends you these questions:

These questions share a pattern: the answer depends on relationships between tables.

You could manually copy customer names into every order row. But then changing a customer's name means updating it in several places. Keeping customers and orders separate gives us one place to maintain the customer record.

A join brings related information together when we need to query it.