WITH MedianValues AS ( SELECT country, PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY daily_vaccinations) AS median_vaccinations FROM country_vaccination_stats WHERE daily_vaccinations IS NOT NULL GROUP BY country ), ZeroCountries AS ( SELECT DISTINCT country, 0 AS median_vaccinations FROM country_vaccination_stats WHERE country NOT IN (SELECT country FROM MedianValues) ) UPDATE country_vaccination_stats SET daily_vaccinations = COALESCE(mv.median_vaccinations, zc.median_vaccinations) FROM country_vaccination_stats cvs LEFT JOIN MedianValues mv ON cvs.country = mv.country LEFT JOIN ZeroCountries zc ON cvs.country = zc.country WHERE daily_vaccinations IS NULL;