Skip to content

Calculated Columns

Daniel Cortes edited this page Jul 31, 2024 · 3 revisions

So how do we write SQL to automatically do this calculation for us for each individual row?

We can run the following calculation:

SELECT name, population / area FROM cities;

So in this case we are doing a calculation. When we run this query, we get the name of each city and the population density to it.

We can use many different math operators, we can find the exponent between two columns.

With the above calculation you will get a query result with ?Column?. This is PostgreSQL recognizing that we are doing a calculation before retrieving some data, but it does not know what to call it, we can fix that by doing the following:

SELECT
  name,
  population / area AS population_density
FROM
  cities;
Clone this wiki locally