Explain Codes LogoExplain Codes Logo

How to join on multiple criteria, returning all combinations of both criteria?

sql
join
sqlfiddle
best-practices
Alex KataevbyAlex Kataev·Jan 11, 2025
TLDR

Execute a quick join with all criteria combinations using a CROSS JOIN and filter with a WHERE clause like this:

SELECT a.*, b.* FROM TableA a CROSS JOIN TableB b WHERE a.Criterion1 = b.Criterion1 AND a.Criterion2 = b.Criterion2;

It pairs every row from TableA with TableB and returns rows where both criteria match.

Join with consistent data types and distinct values

For a successful join on multiple criteria, ensure data types are consistent on both tables - mismatch could yield bizarre results. To eliminate repeated results, use the SELECT DISTINCT clause:

SELECT DISTINCT a.Column1, a.Column2, b.Column3, b.Column4 FROM TableA a CROSS JOIN TableB b WHERE a.Criterion1 = b.Criterion1 AND a.Criterion2 = b.Criterion2;

With the DISTINCT clause, your array of results will be truly unique - just like each snowflake in a snowfall! ❄️

Including non-matching records

If you wish to fetch all records from one table even if they are unmatched in the other, employ a LEFT OUTER JOIN:

SELECT a.*, b.* FROM TableA a LEFT OUTER JOIN TableB b ON a.Criterion1 = b.Criterion1 AND a.Criterion2 = b.Criterion2;

It's the charitable nature of LEFT OUTER JOIN to include everyone, regardless of their matching status - Good Guy Greg approves! 👍

Customized sorts and complex filters

For result sets requiring specific orders or complex conditions, utilise subqueries, GROUP BY, HAVING, and ORDER BY:

SELECT a.*, b.* FROM TableA a JOIN (SELECT * FROM TableB WHERE Condition = 'Value') b ON a.Criterion1 = b.Criterion1 WHERE a.Criterion2 IN (SELECT DISTINCT Criterion2 FROM TableB) ORDER BY a.Criterion1, a.Criterion2;

As they say, "Order is half of life". Using ORDER BY helps you to find the other half!

Aggregation operations and set unions

To manage merging, summarization, and non-matching records, UNION ALL and aggregation come to the rescue:

SELECT a.Criterion1, SUM(a.Value) as TotalValue FROM TableA a JOIN TableB b ON a.Criterion1 = b.Criterion1 GROUP BY a.Criterion1 UNION ALL SELECT b.Criterion2, SUM(b.Value) FROM TableB b LEFT JOIN TableA a ON b.Criterion2 = a.Criterion2 WHERE a.Criterion2 IS NULL GROUP BY b.Criterion2;

Perfect for the times when you need to have your data cake and eat it too!

Using SQLFiddle for testing

Before finalizing your SQL strategy, remember: "Measure twice, cut once":

  • Create several scenarios with sample data.
  • Observe the results visually to confirm correctness.
  • Adjust and refine your query for real-world use.

Clear naming in SQL code

Avoid confusion in joins by explicitly naming columns, especially when they share the same name in multiple tables:

SELECT a.Name AS AName, b.Name AS BName, ... FROM TableA a JOIN TableB b ON a.ID = b.ForeignID;

Remember, clarity is king in code! 👑