Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL LEFT JOIN with WHERE and SUBSTR

I want to use SQL to left join two tables but only where the common column fits a substring criteria. How can this be accomplished?

CREATE TABLE MY_JOIN AS
    SELECT A.*, B.*
FROM DATA.TABLE_B AS B
LEFT JOIN DATA.TABLE_A AS A ON A.COMMON = B.COMMON
WHERE SUBSTR(A.COMMON,1,5) IN ('90210', '90211', '90212')

There are other questions that address using a left join with a where clause but do not specifically address using a substring function within the where clause.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Simply move the condition to the LEFT JOIN clause

CREATE TABLE MY_JOIN AS
    SELECT A.*, B.*
FROM DATA.TABLE_B AS B
LEFT JOIN DATA.TABLE_A AS A ON A.COMMON = B.COMMON 
                            and SUBSTR(A.COMMON,1,5) IN ('90210', '90211', '90212')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading