Data Engineering

Why a SQL Join Can Double Your Report Total

Huwell Consultancy editorial2 min read

A report total can become wrong even when the SQL runs without an error. One common cause is joining data at different levels of detail. This small example is useful practice for a data interview or a report review.

Start with two orders

Imagine an orders table: order 10 has a total of €100 and order 11 has a total of €50. A separate items table has two rows for order 10 and one row for order 11. These are invented teaching values, not customer data.

Follow the rows after the join

Joining each order to its items produces three rows. The €100 order total appears twice because that order has two items. Adding the repeated order totals now gives €250 instead of the original €150. A join combines matching rows; it does not know which business amount you intend to add. The PostgreSQL join tutorial explains this matching behaviour.

Choose the right level

If you need total order value, calculate it from orders at one row per order. If you need item-level information too, first decide what one result row should represent. You may need to summarise items by order before joining. Do not add DISTINCT as a quick fix without understanding which rows it removes.

Check before trusting the number

  • Count rows before and after the join.
  • Check whether the join key is unique on each side.
  • Test one order with several items.
  • Compare the final total with a known small example.

In an interview, explain the repeated rows before suggesting a query change. That shows you understand the data, not just SQL syntax.

Sources and further reading

Browse current technology jobs in Malta →

EXPLORE THE NEXT STEP

Discuss the work you want to do.

Browse current technology vacancies with Huwell Consultancy and ask us about the responsibilities that matter to you.

Explore opportunities
KEEP EXPLORING

More guidance for your next decision