Lesson

MySQL ATAN2() Function

10 min reading
Free Course

MySQL ATAN2() Function: Full-Circle Angles from X and Y Coordinates

The ATAN2(y, x) function returns the arc tangent of two numeric values y and x in MySQL. It behaves like computing ATAN(y / x), except MySQL checks the signs of both inputs to pick the exact quadrant.

Because it inspects both signs separately, ATAN2() returns angles across the full circle from -PI() to PI() radians. It also handles x = 0 gracefully without triggering division by zero.

Syntax

ATAN2(y, x)
  • y: The vertical (sine-axis) numeric coordinate, passed first.
  • x: The horizontal (cosine-axis) numeric coordinate, passed second.

Practical Example

Suppose demo_orders tracks drone delivery vectors using north_km (y) and east_km (x) offsets from a hub. You want to calculate each route's heading angle in degrees without risking division by zero on due-north flights.

SELECT
    order_id,
    north_km,
    east_km,
    ROUND(ATAN2(north_km, east_km), 4) AS angle_radians,
    ROUND(DEGREES(ATAN2(north_km, east_km)), 2) AS angle_degrees
FROM demo_orders
WHERE order_id BETWEEN 701 AND 704;
order_id north_km east_km angle_radians angle_degrees
701 5.0 0.0 1.5708 90.00
702 0.0 -4.0 3.1416 180.00
703 -3.0 -3.0 -2.3562 -135.00
704 NULL 2.0 NULL NULL

Order 701 travels due north (east_km = 0.0) and resolves cleanly to 90.00 degrees. Order 704 has a NULL offset, so ATAN2() returns NULL.

Common Mistakes & NULL Behavior

  • Putting X before Y: Developers familiar with (x, y) coordinate pairs often write ATAN2(x, y) by mistake. MySQL always expects ATAN2(y, x).
  • Missing one argument: Calling ATAN2(5) throws a syntax error because ATAN2() strictly requires two arguments. Use ATAN(5) for single-argument calls.
  • NULL propagation: If y is NULL, x is NULL, or both are NULL, ATAN2() returns NULL.

Frequently Asked Questions

Does ATAN2(0, 0) raise a division-by-zero error in MySQL?

No. MySQL defines ATAN2(0, 0) as 0, so vertical or zero-length vectors never raise a division error.

How do I convert ATAN2() output to a 0–360 compass range?

Use MOD(DEGREES(ATAN2(y, x)) + 360, 360) to shift negative angles like -135 into 225 degrees.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
MySQL Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum