Share via

SQL Join returns all rows

ANB 181 Reputation points
2021-11-04T20:48:37.737+00:00

I am trying to do a select on 2 tables and return data if the Table1.codeId is presented on Table2 OR if Table1.codeId = 0.
However it's returning all the data from Table2.

    Table1 {
      name nvarchar,
      codeId int
    }

    Table1 Records
    Bob, 1
    John, 2
    Chris, 0

    Table2 {
      id int,
      codeName nvarchar
    }

    Table2 Records
    1, Engineer
    2, Doctor
    3, Dentist
    4, Pilot
    5, Mechanic

    SELECT t1.name, t2.codeName
    FROM dbo.Table1 t1, dbo.Table2 t2
    WHERE (t1.codeId = t2.id OR t1.codeId = 0)

I just want to return:
Bob, 1
John, 2
Chris, 0

How can I do it ?
Thx

SQL Server | Other
0 comments No comments

Answer accepted by question author

  1. Viorel 126.9K Reputation points
    2021-11-04T20:57:15.423+00:00

    Try two queries:

    select * 
    from Table1
    where codeId = 0 or codeId in (select id from Table2)
    
    select t1.name, t2.codeName
    from Table1 t1
    left join Table2 t2 on t2.id = t1.codeId
    
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.