|
Finding the difference between two tables
EXAMPLE DATABASE: Training2DATA INPUTThe inputs are tables from the Training2.mdb database namely, asia and eastern_asia. The aim is to identify the countries that are in one table, but are not included in the other table. The asia table contains the country code, name and population of some countries in Asia.
QUERY country_missing_in_asiaSELECT cnt_code, cnt_name, cnt_pop, "eastern_asia" AS source FROM eastern_asia WHERE cnt_code NOT IN (SELECT cnt_code FROM asia); The country_missing_in_asia query lists the East Asian countries which are not included in the Asia table.
DISCUSSIONThe query requires the country code, name, population and the source table. The phrase "eastern_asia" AS source in the SELECT statement is an added column stating the source table, which is eastern_asia. To identify the East Asian countries that are not included in the Asia table, it is declared in the WHERE statement that the country code from eastern_asia table must be NOT IN the list of country codes in the asia table. With this simple SQL statement, there was already a comparison made between the two tables, plus the output of the difference between them.
QUERY country_differencesSELECT cnt_code, cnt_name, cnt_pop, "eastern_asia" AS source FROM eastern_asia WHERE cnt_code NOT IN (SELECT cnt_code FROM asia); UNION ALL SELECT cnt_code, cnt_name, cnt_pop, "asia" AS source FROM asia WHERE cnt_code NOT IN (SELECT cnt_code FROM eastern_asia); The country_differences query lists the East Asian countries which are not included in the Asia table, and also, the list of Asian countries which are not in the Eastern Asia table.
DISCUSSIONThe first SELECT statement does the same as the previous query which retrieves the East Asian countries that are not included in the asia table. The UNION ALL statement combined head-to-tail the countries that appear in the asia table, but are not included in the eastern_asia table.
Last modified September 23, 2008 7:22 am
|