How to Find Square of a Number in PostgreSQL

Sometimes we need to find the square of a given number number in PostgreSQL. PostgreSQL offers two approaches for finding the square of a number. This blog will focus on the three methods to calculate the square of a number in Postgres. These two methods are:

  • Method 1: Using Multiplication operation.
  • Method 2: Using Power Function.

Let’s discuss these methods one by one.

How to Find the Square of a Number in PostgreSQL?

PostgreSQL offers two approaches for finding the square of a number. Let’s discuss.

Method 1: Using the Multiplication operation

By multiplying the values/number by itself, we may find its square. This is a very simple method and the query can be written as follows:

SELECT number*number;

We need to specify the numbers in the above query to find the square of that specific number.

img

To operate this method on a table we need to have a table of numbers consider the following table named num:

Now we will execute the following query to get the square of the numbers:

SELECT
  *,
  x * x AS square
FROM num;

The output of the above query will be a table having 2 columns one containing numbers and the second one containing their squares like this:

img

Method 2: Using Power Function

We can also find the square of the function using the POWER() function. This function takes two arguments as input. The first parameter/argument is the number itself and the second parameter is the power of that number. In the case of square, the second argument will always be 2. If we want to find the square of 3 we will write the following query:

SELECT POWER(3,2);

The output will be 9.

If we want to get a square of all the entries of a column of a table, below is the query for calculating the square using this power method:

SELECT *,
 POWER( x, 2) AS square
FROM num;

This will give the square of each entry of a column like this:

img

Conclusion

There are two ways to calculate/get the square of a number. The first and simplest way is to apply the multiplication operation i.e. by multiplying the number by itself. The second is the POWER() function. This function takes in the number and the power to apply to that number. In the case of square power always has to be 2.