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)Code language: SQL (Structured Query Language) (sql)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;Code language: SQL (Structured Query Language) (sql)Result:
result
------
4.0Code language: SQL (Structured Query Language) (sql)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)
);Code language: SQL (Structured Query Language) (sql)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);Code language: SQL (Structured Query Language) (sql)Third, retrieve data from the coordinates table:
SELECT
id,
x,
y
FROM
coordinates;Code language: SQL (Structured Query Language) (sql)Output:
id | x | y
---+----+----
5 | -3 | 4
2 | -1 | 7
3 | 0 | 0
1 | 2 | 3
4 | 9 | -5
(5 rows)Code language: plaintext (plaintext)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;Code language: SQL (Structured Query Language) (sql)Output:
distance
--------------------
5.0
7.0710678118654755
0.0
3.605551275463989
10.295630140987
(5 rows)Code language: plaintext (plaintext)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;Code language: SQL (Structured Query Language) (sql)Output:
distance
--------
5.00
7.07
0.00
3.61
10.30
(5 rows)Code language: plaintext (plaintext)Summary #
- Use the SQL Server
SQRT()function to calculate the square root of a number.