Home > Database > Mysql Tutorial > How Can I Use Calculated Columns from the Same Query in PostgreSQL?

How Can I Use Calculated Columns from the Same Query in PostgreSQL?

Linda Hamilton
Release: 2025-01-14 07:29:47
Original
620 people have browsed it

How Can I Use Calculated Columns from the Same Query in PostgreSQL?

Using computed columns in the same query in PostgreSQL

PostgreSQL does not allow calculations using aliases directly within the same SELECT statement. For example, the following SQL statement will report an error:

<code class="language-sql">SELECT cost_1, quantity_1, cost_2, quantity_2, 
(cost_1 * quantity_1) AS total_1,
(cost_2 * quantity_2) AS total_2,
(total_1 + total_2) AS total_3
FROM data;</code>
Copy after login

This is because when PostgreSQL calculates total_3, total_1 and total_2 have not been defined yet.

The solution is to use a subquery (derived table):

<code class="language-sql">SELECT cost_1,
       quantity_1,
       cost_2,
       quantity_2,
       total_1 + total_2 AS total_3
FROM (
    SELECT cost_1, 
           quantity_1, 
           cost_2, 
           quantity_2, 
           (cost_1 * quantity_1) AS total_1,
           (cost_2 * quantity_2) AS total_2
    FROM data
) t;</code>
Copy after login

By creating the subquery t, we define total_1 and total_2 as available columns in the outer SELECT statement. There is no performance penalty with this approach. The outer query references the result set of the inner query so that total_3 can be calculated correctly.

The above is the detailed content of How Can I Use Calculated Columns from the Same Query in PostgreSQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template