I am working through the book Practical SQL by Anthony DeBarros. I am on chapter 6 and came across this code:
SELECT county_name AS county,
state_name AS state,
area_water::numeric / (area_land + area_water) * 100 AS pct_water
FROM us_counties_pop_est_2019
ORDER BY pct_water DESC;
on line 3, author uses CAST to change the data type of area_water to numeric, in doing so he uses the short-form notation for CAST from PostgreSQL.
I have been trying to use the CAST notation instead of the double colon, and I have been unable to get a correct query. Can someone help me with the correct syntax for the query here?
First Code from book
SELECT county_name AS county,
state_name AS state,
area_water::numeric / (area_land + area_water) * 100 AS pct_water
FROM us_counties_pop_est_2019
ORDER BY pct_water DESC;
Correct Result:
"Keweenaw County" "Michigan" 90.94723747453215452900
"Leelanau County" "Michigan" 86.28858968116583102500
"Nantucket County" "Massachusetts" 84.79692499185512352300
"St. Bernard Parish" "Louisiana" 82.48371149202893908400
"Alger County" "Michigan" 81.87221940647501072300
Code I tried for CAST notation:
SELECT county_name AS county,
state_name AS state,
area_water CAST (area_water AS numeric)
area_water / (area_land + area_water) * 100 AS pct_water
FROM us_counties_pop_est_2019
ORDER BY pct_water DESC;
Result:
ERROR: syntax error at or near "("
LINE 3: area_water CAST (area_water AS numeric)
^
What is it that I am doing wrong here?
Try this one:
CAST() is a function and in your case, you need the result from this function to do the calculation. Use this order and you will be fine.