How to Use SQRT Function in MySQL: Syntax and Examples
In MySQL, you use the
SQRT() function to calculate the square root of a number. Simply pass the number or column name inside the parentheses like SQRT(16), which returns 4.Syntax
The SQRT() function takes one numeric argument and returns its square root. If the argument is negative, the function returns NULL.
SQRT(number): Calculates the square root ofnumber.
sql
SELECT SQRT(number) AS square_root FROM your_table;
Example
This example shows how to calculate the square root of a fixed number and a column value in a table.
sql
SELECT SQRT(25) AS sqrt_of_25; -- Assuming a table named 'numbers' with a column 'value' SELECT value, SQRT(value) AS sqrt_value FROM numbers;
Output
sqrt_of_25
5.0
value | sqrt_value
----- | ----------
16 | 4.0
9 | 3.0
25 | 5.0
Common Pitfalls
Common mistakes when using SQRT() include:
- Passing a negative number, which returns
NULLbecause square root of negative numbers is not defined in real numbers. - Using non-numeric data types, which can cause errors or unexpected results.
Always ensure the input is a non-negative number.
sql
SELECT SQRT(-9) AS invalid_sqrt; -- Returns NULL -- Correct usage: SELECT SQRT(9) AS valid_sqrt; -- Returns 3
Output
invalid_sqrt
NULL
valid_sqrt
3.0
Quick Reference
| Function | Description | Example | Result |
|---|---|---|---|
| SQRT(number) | Returns square root of number | SQRT(16) | 4.0 |
| SQRT(0) | Square root of zero | SQRT(0) | 0.0 |
| SQRT(-1) | Negative input returns NULL | SQRT(-1) | NULL |
Key Takeaways
Use SQRT(number) to get the square root of a non-negative number in MySQL.
SQRT returns NULL for negative inputs because square roots of negative numbers are not real.
Ensure the input to SQRT is numeric and non-negative to avoid errors or NULL results.
You can use SQRT on both fixed numbers and numeric columns in tables.