How to Calculate a Square Root in SQL
Database:
Operators:
Table of Contents
Problem
You want to find the square root of a number in SQ:.
Example
You want to compute the square root of all numbers in the column number
from the table data
.
number |
---|
9 |
2 |
1 |
0.25 |
0 |
-4 |
Solution
SELECT number, SQRT(number) AS square_root FROM data;
The result is:
number | square_root |
---|---|
9 | 3 |
2 | 1.4142135623731 |
1 | 1 |
0.25 | 0.5 |
0 | 0 |
-4 | error |
Discussion
To compute the square root of a number in SQL, use the SQRT()
function. This function takes a number
as its argument and returns the square root.
Note that there is no real square root from a negative number (complex numbers aren't supported) – hence the error.
Also, for most numbers (e.g., 2, 2.5, 3, 3.2 etc.) the square root is an irrational number – in the square_root
column you won't see the exact results, only the first several digits of their decimal expansion.