Select rows that are not present in the table

All we need is an easy explanation of the problem, so here it is.

I have two tables student table and fee table:

First Table (Student):

std_id std_name
1 A
2 B
3 C
4 D
5 E
6 F

Second Table(Fee):

fid std_id amount
1 1 500
2 2 500
3 4 500

I want to fetch rows of those students from fee table who are not paid amount. In above example want to fetch the names of std_id 3,5 and 6.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Common anti-semijoin.

Either

SELECT *
FROM table1
LEFT JOIN table2 USING (std_id)
WHERE t2.std_id IS NULL

or

SELECT *
FROM table1
WHERE NOT EXISTS ( SELECT NULL
                   FROM table2
                   WHERE table1.std_id = table2.std_id )

or

SELECT *
FROM table1
WHERE std_id NOT IN ( SELECT std_id 
                      FROM table2 )

First 2 variants have approximately the same effectiveness (depends on data statistic and indices presence, sometimes these queries may even produce the same execution plan). Last variant has least effectiveness approximately always.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply