Skip to content
Advertisement

Joining two tables to keep selected values and nulls

I have got two tables that I need to join. The second table is used to filter the records from the first table.

  • table1.parameter
  • table2.parameter; table2.parameter_group

The result should include all records from table1 for a certain parameter_group but also records where the parameter is null.
What I have is:

table1 LEFT JOIN table2  
ON table1.parameter=table2.parameter  
WHERE table2.parameter_group IS 'A' OR table1.parameter IS NULL

My question is – is this the most effective way of achieving the goal? Point is that each of the filters (parameter_group IS ‘A’ OR table1.parameter IS NULL) target just few percents of records from the very large table1. I assume this is about clarifying (explaining to me) the processing order… Thanks for help.

Advertisement

Answer

If you want all rows in table1 along with matches from table2 for parameter_group = 'A', then move the condition to the ON:

table1 LEFT JOIN
table2  
ON table2.parameter = table1.parameter  AND
   table2.parameter_group = 'A' 

Your method does not always work. If table2 has a parameter that is not 'A', then it will be filtered out.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement