Search code examples
sqlgoogle-bigquerydml

SQL Update based on secondary table in BQ


I have 2 tables, 1 containing the main body of information, the second contains information on country naming convensions. in the information table, countries are identified by Name, I would like to update this string to contain an ISO alpha 3 value which is contained in the naming convention table. e.g turning "United Kingdom" -> "GBR"

I have wrote the following query to make the update, but it effects 0 rows

UPDATE 
    `db.catagory.test_votes_ds`
SET 
    `db.catagory.test_votes_ds`.country =  `db.catagory.ISO-Alpha`.Alpha_3_code
FROM
    `db.catagory.ISO-Alpha`
WHERE 
    `LOWER(db.catagory.ISO-Alpha`.Country) = LOWER(`db.catagory.test_votes_ds`.country) 

I've done an inner join outside of the update between the 2 to make sure that the values are compatable and it returns the correct value, any ideas as to why it isn't updating?

The join used to validate the result is listed below, along with the result:

SELECT 
    `db.catagory.test_votes_ds`.country, `db.catagory.ISO-Alpha`.Alpha_3_code
from 
    `db.catagory.test_votes_ds`
inner join 
    `db.catagory.ISO-Alpha` 
on 
    LOWER(`db.catagory.test_votes_ds`.country) = LOWER(`db.catagory.ISO-Alpha`.Country)
1,Ireland,IRL
2,Australia,AUS
3,United States,USA
4,United Kingdom,GBR

Solution

  • This is not exactly an answer. But your test may not be sufficient. You need to check where the values do not match. So, to return those:

    select tv.*
    from `db.catagory.test_votes_ds` tv left join
         `db.catagory.ISO-Alpha` a
         on LOWER(tv.country) = LOWER(a.Country)
    where a.Country IS NULL;
    

    I suspect that you will find countries that do not match. So when you run the update, the matches are getting changed the first time. Then the non-matches are never changed.