Question

SELECT CountryCode, Name AS Country, Language
FROM Country INNER JOIN CountryLanguage
ON Country.Code = CountryLanguage.CountryCode
WHERE Language = 'German'
ORDER BY Country;

How would you use EXISTS and a subquery with this SELECT Statement?

Was it helpful?

Solution

This should yield the same result and uses EXISTS:

select countrycode, name as country, language
  from country y
 where exists (select 'fish'
          from countrylanguage x
         where x.countrycode = y.code
           and x.language = 'German')
 order by country;

With an EXISTS subquery, if the subquery returns anything, the condition passes, and if it returns no rows, it fails, it doesn't matter what you put in the select statement (notice I typed in 'fish'). But that subquery will still return a row in any situation where the country has a row on countrylanguage where the language is german, and so for the rows of country that are applicable to you, the condition passes, and so it filters the same way.

OTHER TIPS

Thanks for all the tips. I was able to patch together a solution with EXISTS and a subquery that yields the same results as my original SELECT Statement.

SELECT CountryCode, Name AS Country, Language
FROM CountryLanguage AS X INNER JOIN Country AS Y
ON X.CountryCode = Y.Code
WHERE EXISTS
    (
    SELECT 'German'
    FROM CountryLanguage AS X
    WHERE X.CountryCode = Y.Code
    AND X.Language = 'German'
    )
AND X.Language = 'German'
ORDER BY Country;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top