Summary: in this tutorial, you will learn how to use the SQL Server SQRT() function to calculate the square root of a number.
Introduction to the SQL Server SQRT() function #
The SQRT() function is a useful mathematical function that allows you to calculate the square root of a number.
The following shows the syntax of the SQRT() function:
SQRT(number)
In this syntax, the number can be a float or any number that can be implicitly converted to a float. Also, it can be a numeric expression.
The SQRT() function returns the square root of the number with the type of float. It returns NULL if the number is NULL.
SQL Server SQRT() function examples #
Let’s take some examples of using the SQRT() function.
1) Basic SQRT() function example #
The following statement uses the SQRT() function to return the square root of 16:
SELECT SQRT(16) AS result;
Result:
result
------
4.0
The query returns 4.0 as the square root of 16.
2) Using SQRT() function to calculate distance #
First, create a table called coordinates that stores the x and y-coordinates of points in two-dimensional space:
CREATE TABLE coordinates (
id INT IDENTITY PRIMARY KEY,
x NUMERIC,
y NUMERIC,
UNIQUE (x, y)
);
Second, insert some rows into the coordinates table:
INSERT INTO coordinates (x, y)
VALUES
(2, 3),
(-1, 7),
(0, 0),
(9, -5),
(-2.5, 3.5);
Third, retrieve data from the coordinates table:
SELECT
id,
x,
y
FROM
coordinates;
Output:
id | x | y
---+----+----
5 | -3 | 4
2 | -1 | 7
3 | 0 | 0
1 | 2 | 3
4 | 9 | -5
(5 rows)
Finally, calculate the distance of each point from the origin (0,0) using the SQRT() function:
SELECT
SQRT(x * x + y * y) AS distance
FROM
coordinates;
Output:
distance
--------------------
5.0
7.0710678118654755
0.0
3.605551275463989
10.295630140987
(5 rows)
To make the result more readable, you can use the ROUND() function to round the distances to numbers with two precisions and the function to cast them to a number with two decimal places.CAST()
SELECT
CAST(ROUND(SQRT(x * x + y * y), 2) AS DEC(5, 2)) AS distance
FROM
coordinates;
Output:
distance
--------
5.00
7.07
0.00
3.61
10.30
(5 rows)
Summary #
- Use the SQL Server
SQRT()function to calculate the square root of a number.
Thank you for your feedback!