1

There are two tables table1 and table2 i want to join these tables and expect to retrieve rows which are not equal to table1 as there are rows which are in the both tables.

Table1

ID   NAME   Dept
 1   B     Finance
 2   R     HR
 3   B     CDU

Table2

ID  PASSPORT
1   Yes
2   No

it is not working

SELECT table1.ID, table1.NAME, table1.Dept FROM TABLE1 INNER JOIN TABLE2 ON 
TABLE1.ID != TABLE2.ID

Expected Result

  ID   NAME  DEPT 
  3     B     CDU
11
  • show your expected result Commented Jul 11, 2017 at 3:40
  • ok let me edit it Commented Jul 11, 2017 at 3:40
  • Try FULL OUTER JOIN instead of INNER JOIN so the columns you're selecting exist Commented Jul 11, 2017 at 3:43
  • Do you want values that are exclusively in one table or the other? i.e. only in table1 or only in table2. Or values that are in table1 but not in table2? Or values that are in table2 but not in table1? Commented Jul 11, 2017 at 3:43
  • Please show us your expected output. Commented Jul 11, 2017 at 3:45

2 Answers 2

4

Use a left join to and where clause to grab the values that are only in table1

select
  table1.id,
  table1.name,
  table1.Dept
from
  table1
  left join table2 on table2.id = table1.id
where
  table2.id is NULL;

Output for the above Query:

output

A left join will insert a null value if the record from the second table cannot be found. So add in the where clause to grab all results that could not be found in the second table.

Here is a better description of using a left join https://www.w3schools.com/sql/sql_join_left.asp

Sign up to request clarification or add additional context in comments.

3 Comments

it is not going to work coz it is going to show all left table rows in table1, please review my expected result
No it should work. I've been writing SQL for a while it gets what you want just add in the columns you care about.
Let me try again
1

Try this query --

SELECT ID
    ,NAME
    ,Dept
FROM TABLE1
WHERE ID NOT IN (
        SELECT DISTINCT ID
        FROM Table2
        WHERE ID IS NOT NULL
        );

7 Comments

WHERE ID IS NOT NULL is unnecessary on since it is likely ID is a primary key and would always have a value.
Yes. I didn't know about that so I just took care of it by adding it.
@Adam - It is needed NOT IN will fail when sub-query returns any NULL value... at least in Sql Server
I was assuming it was a primary key and thus never nullable. He wasn't.
in the second table it is foreign key Adam, for test i named it as ID
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.