- Joining 2 tables (orders, addresses)
- Orders contains columns delivery_address_id (contains NULL values) and invoice_address_id (does NOT contain NULL values)
- Addresses contains id column (does NOT contain NULL values)
Primarily, the LEFT JOIN must be performed on orders.delivery_address_id. However, in the case when its value is NULL in the row, perform LEFT JOIN on orders.invoice_address_id.
How do I deal with this?
I tried the operator OR
but the result was not correct. I was also thinking about a CASE WHEN statement. My expectations are to get the LEFT JOIN working.
2
Answers
You can use the operator
OR
in theON
clause:Or, use
COALESCE()
:So, you want to join on
delivery_address_id
, but sometimes it’sNULL
, so you needinvoice_address_id
to be a fallback.These situations are where the COALESCE function really shines.
COALESCE(delivery_address_id, invoice_address_id)
will resolve to the delivery address ID if it isn’tNULL
, otherwise it will resolve to the invoice address ID instead.Thus we can achieve the join you want: