How to Multiply Two Table Columns in PostgreSQL

PostgreSQL users often need to perform mathematical operations on mathematical data, such as addition, subtraction, multiplication, and so on. To deal with such cases, Postgres provide various inbuilt operators and functions. For instance, to perform multiplication on two columns of a particular table, the “*” operator is used in PostgreSQL.

This post will explain how to multiply two columns of a particular table in Postgres using the “*” operator.

How to Multiply Two Table Columns in Postgres?

To perform multiplication on tables columns, all you need to do is, specify the “*” operator between the column names, as shown in the following syntax:

SELECT
col_1 * col_2
FROM tab_name;

Here, col_1 and col_2 are the columns to be multiplied while tab_name represents the targeted table.

Example: Multiplying Two Columns

We have a sample table named “product_details” that contains the following records:

SELECT * FROM product_details
ORDER BY pro_id;
img

Suppose we want to get the total price of each product. To do so, we need to multiply the “pro_price” column with the “pro_quantity” column:

SELECT *,
pro_price * pro_quantity AS subtotal 
FROM product_details
ORDER BY pro_id;

In the above query:

- The SELECT * query is used to fetch all columns of the “product_details” table.
- The “*” operator is used between the “pro_price” and “pro_quantity” columns of the selected table to get the total price.
- The column alias “AS” is used to assign a temporary name to the resultant column.
- The table’s records will be sorted according to the “pro_id” column.

img

The output snippet shows that the multiplication has been successfully performed on the selected columns.

That was all about multiplying two columns in PostgreSQL.

Conclusion

To perform multiplication on two columns of a particular table, the “*” operator is used in PostgreSQL. For this purpose, all you need to do is, specify the “*” operator between the selected columns. Consequently, the stated operator will perform the multiplication on the selected columns and retrieve the result in a new column. This blog post has demonstrated the use of the “*” operator in PostgreSQL using appropriate examples.