15

I have table 1, all_countries, as follows-

id   |  country
------------------
1    |  USA
2    |  China
3    |  India
4    |  France
5    |  UK
6    |  Australia

and I also have table 2, supported_countries, as -

id   |  country
------------------
1    |  USA
2    |  China

Now I need a query that would give me result that includes all countries that ARE NOT supported

So as per above example I should get

India
France
UK
Australia

I am using the following query -

SELECT ac.country FROM all_countries ac INNER JOIN supported_countries sc ON sc.country_name != ac.country_name

It works fine, except when supported_countries table is empty, it doesn't show any records. How to achieve this result?

skos
  • 4,102
  • 8
  • 36
  • 59

4 Answers4

43

A LEFT JOIN will do that elegantly;

SELECT a.* 
FROM all_countries a
LEFT JOIN supported_countries s
  ON a.country = s.country
WHERE s.id IS NULL;

Demo here.

Joachim Isaksson
  • 176,943
  • 25
  • 281
  • 294
5

Try something like the following:

SELECT * FROM all_countries 
  WHERE country NOT IN (SELECT country FROM supported_countries)
Abel
  • 56,041
  • 24
  • 146
  • 247
IT ppl
  • 2,626
  • 1
  • 39
  • 56
  • 8
    Subqueries are often [less performant](http://stackoverflow.com/questions/3856164/sql-joins-vs-sql-subqueries-performance) than explicit joins. They are easier to read, but do not scale well. – terrabruder Mar 03 '14 at 22:55
2
SELECT ac.country FROM all_countries ac 
LEFT JOIN supported_countries sc ON 
sc.country_name = ac.country_name
WHERE ISNULL(sc.country_name)
toonice
  • 2,211
  • 1
  • 13
  • 20
Nilesh
  • 1,149
  • 9
  • 14
0

While @Joachim Isaksson gave me the clue, I tested this very similar query and worked on my database by replacing variables.

SELECT * FROM all_countries 
LEFT JOIN supported_countries ON all_countries.id = supported_countries.id 
WHERE supported_countries.id IS NULL

I gave the question and that Joachim's answer my thumbs up. Cheers !

Luis H Cabrejo
  • 302
  • 1
  • 8