QUESTION: IS IT POSSIBLE TO CAST WITH ALIAS? WHEN I TRIED CASTING WITH ALIAS IN THE PROJECT BELOW I GOT AN ERROR MESSAGE
MY CODE USING AN ALIAS FOR CASTING
SELECT f.name country,
f.population as total_pop,
cast(c.urban_pop as float) /Cast(total_pop as float) as urban_pct from facts f
inner JOIN (select facts_id,SUM(population) as urban_pop from cities group by facts_id) c ON c.facts_id=f.id
order by urban_pct`
I assumed that since I have given an alias of total_pop to f.population, I could use the alias when casting f.population into a float
You can’t use an alias in the same
You will have to use
is your statement based on how SQL runs a query? . Hence the reason why you can’t use an alias in the same
could you explain further using how the query would run if you use an alias in the same SELECT statement. hence were the error would be generated
Yes, that’s the case. That’s just how the language is designed based on what I came across when I tried to search for this.
There might be a variant of SQL where this is possible (without using subqueries or
WITH), but I couldn’t really find any. Most, if not all, don’t allow for this.