CAST placement in SQL

Hey there! qq about CAST and where this goes when executing an aggregation? Why In the below query does CAST not belong in the 4th column on both c.urban_pop as well? I wanted tot type this (CAST(c.urban_pop AS FLOAT) / CAST(f.population AS float))?

Here is the correct query:
SELECT
f.name AS country,
c.urban_pop,
f.population AS total_pop,
(c.urban_pop / CAST(f.population AS float)) AS urban_pct
FROM facts as f
INNER JOIN (SELECT
facts_id,
SUM(population) urban_pop
FROM cities
GROUP BY 1) AS c ON c.facts_id = f.id
WHERE urban_pct > .5
ORDER BY urban_pct ASC;

There is an existing question similar to yours that should help - Why is CAST placed in denominator ? Why not placed in both numerator and denominator?

For any future questions/posts please make sure that when you ask questions -

  1. Share the link to the Mission/Mission Step
  2. Try to apply the appropriate tags to the question if possible
  3. Share your code, in text form and properly formatted.

You can also refer to Introducing guidelines for all technical questions in our Community and Guide: How to Ask a Good Question as well.

1 Like