How Atan2() Works in PostgreSQL

In PostgreSQL, atan2() is a trigonometric function that returns the arctangent, or inverse tangent, of the specified x and y coordinates in radians.

Syntax

The syntax goes like this:

atan2(y, x)

Where x and y are double precision values.

The arctangent is the angle from the x-axis to a line containing the origin (0, 0) and a point with coordinates (x, y)

Example

Here’s an example to demonstrate how it works.

SELECT atan2(1, 1);

Result:

0.7853981633974483

This returned the arctangent of the point 1,1 in radians.

Negative Argument

The argument can also be negative.

SELECT atan2(-1, -1);

Result:

-2.356194490192345

This returned the arctangent of the point -1,-1 in radians.

Atan2() vs Atan(x/y)

Using atan2(x, y) is functionally equivalent to using atan(x/y).

However, one difference is that, if you specify a y value of zero, atan2() won’t return an error, whereas atan() will.

Here’s an example using atan2():

SELECT atan2(1, 0);

Result:

1.5707963267948966

And here’s what we get with atan() when trying to divide by zero:

SELECT atan(1/0);

Result:

ERROR: division by zero

Return the Angle in Degrees

As mentioned, atan2() returns its argument in radians. To get it in degrees, use the atan2d() function.

The atan2d() function works exactly the same as atan2(), except that its argument is returned in degrees instead of radians.