sql – Why isn't OR good in a LEFT JOIN?

Question:

I'm creating a query and my pull request came back because the code tester found that OR is not good for table relationship.

Example:

  FROM LEFT JOIN administracao.cidade cid
    ON (cid.cid_cd_cidade = cec.cec_cd_cidade)
    OR (cid.cid_cd_cidade = cli.cli_cd_cidade)

What would you recommend instead?

Answer:

Using OR with LEFT JOIN makes the query slow, an alternative is to use UNION .

  FROM LEFT JOIN administracao.cidade cid
    ON (cid.cid_cd_cidade = cec.cec_cd_cidade)
  UNION
  FROM LEFT JOIN administracao.cidade cid
    On (cid.cid_cd_cidade = cli.cli_cd_cidade)

Take a test by carrying out a consultation, and observe the turnaround time, and mention your experience in the comments.

Scroll to Top