How Pi() Works in PostgreSQL

In PostgreSQL, the pi() function returns the number π.

π constant is a mathematical constant. It is defined as the ratio of a circle’s circumference to its diameter.

Syntax

The syntax goes like this:

pi()

So no arguments are required (or accepted).

Example

Here’s an example of how it works.

SELECT pi();

Result:

3.141592653589793

Expressions

It can be used in an expression.

SELECT pi() * 1000;

Result:

3141.592653589793

Compared With Radians & Degrees

The radians() function converts its argument from degrees to radians.

A full circle is 2π.

Therefore, we can use radians() to return pi by passing in an argument that represents a half circle (i.e. 180).

SELECT radians(180);

Result:

3.141592653589793

Rounding

Here’s an example of combining pi() with round() to round to the nearest integer when using it within an expression.

SELECT round(pi() * 1000);

Result:

3142

Alternatively, you could use a function like ceiling() to explicitly round up, or floor() to explicitly round down.

SELECT 
  ceiling(pi() * 1000),
  floor(pi() * 1000);

Result:

 ceiling | floor
---------+-------
    3142 | 3141

Or if you don’t want any rounding to occur, you could use trunc() to simply truncate the number at the desired position.

SELECT 
  trunc(pi() * 1000),
  trunc(pi() * 10000),
  trunc(pi() * 100000);

Result:

 trunc | trunc | trunc
-------+-------+--------
  3141 | 31415 | 314159