Lesson

MySQL SQRT() Function

10 min reading
Free Course

MySQL SQRT() Function: Calculating Non-Negative Square Roots

The SQRT() function returns the non-negative square root of a number as a DOUBLE. For example, SQRT(64) returns 8, and SQRT(0) returns 0.

Developers use SQRT() in Euclidean distance queries, standard deviation calculations, and square packaging layouts. Unlike languages that throw exceptions on negative square roots, MySQL handles invalid negative domains safely by returning NULL.

Syntax

SQRT(x)
  • x: Numeric expression greater than or equal to 0.

Practical Example

Suppose demo_customers records planar coordinates (coord_x, coord_y) relative to a regional fulfillment center at (0, 0). You can compute the straight-line distance to each customer using SQRT(POW(coord_x, 2) + POW(coord_y, 2)).

SELECT
    customer_id,
    city,
    coord_x,
    coord_y,
    ROUND(SQRT(POW(coord_x, 2) + POW(coord_y, 2)), 2) AS distance_km
FROM demo_customers
WHERE coord_x IS NOT NULL AND coord_y IS NOT NULL;
customer_id city coord_x coord_y distance_km
31 Austin 3.0 4.0 5.00
32 Dallas -6.0 8.0 10.00
33 Waco 0.0 0.0 0.00

For customer 31, 3^2 + 4^2 = 25, and SQRT(25) returns 5.00 km.

Common Mistakes & NULL Behavior

  • Negative inputs return NULL: Calling SQRT(-1) or SQRT(-25) does NOT raise an error in MySQL—it returns NULL because MySQL operates on real numbers, not complex numbers. If your formula can dip slightly negative from floating-point rounding (like -1e-16), clamp it with SQRT(GREATEST(0, expr)).
  • Precision loss on giant integers: Because SQRT() converts inputs to 64-bit DOUBLE (53 bits of significand), huge BIGINT values above 2^53 may lose exactness.
  • NULL propagation: SQRT(NULL) returns NULL.

Frequently Asked Questions

Does SQRT(-1) throw an error in MySQL?

No. MySQL returns NULL for any negative number passed to SQRT(), including -1 and -0.001.

Is SQRT(x) faster or cleaner than POW(x, 0.5)?

Both compute the same value for x >= 0. SQRT(x) is clearer to read and safely returns NULL on negative inputs instead of risking domain errors.

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