SQL Server SQRT()



SQL Server SQRT() Function

The SQL Server SQRT() function returns the square root of a specified number. This function is useful for mathematical calculations that require square root operations.


Syntax

SELECT SQRT(number);

The SQRT() function takes a single argument:

  • number: The number for which to calculate the square root. The value must be non-negative.

Example SQL Server SQRT() Function Queries

Let's look at some examples of SQL Server SQRT() function queries:

1. Basic SQRT() Example

SELECT SQRT(9) AS result;

This query returns the square root of 9. The result will be:

result
------
3

2. SQRT() with a Decimal Number

SELECT SQRT(20.25) AS result;

This query returns the square root of 20.25. The result will be:

result
------
4.5

3. SQRT() with a Column

SELECT number, SQRT(number) AS sqrt_value
FROM sample_numbers;

This query returns the square root of the number column for each record in the sample_numbers table. The result will show the original number and its corresponding sqrt_value.

4. SQRT() with a Variable

DECLARE @num FLOAT;
SET @num = 144;
SELECT SQRT(@num) AS result;

This query uses a variable to store a numeric value and then returns its square root. The result will be:

result
------
12

Full Example

Let's go through a complete example that includes creating a table, inserting data, and using the SQRT() function.

Step 1: Creating a Table

This step involves creating a new table named sample_numbers to store some sample data.

CREATE TABLE sample_numbers (
    id INT PRIMARY KEY,
    number FLOAT
);

In this example, we create a table named sample_numbers with columns for id and number.

Step 2: Inserting Data into the Table

This step involves inserting some sample data into the sample_numbers table.

INSERT INTO sample_numbers (id, number) VALUES (1, 9);
INSERT INTO sample_numbers (id, number) VALUES (2, 20.25);
INSERT INTO sample_numbers (id, number) VALUES (3, 144);
INSERT INTO sample_numbers (id, number) VALUES (4, 0);

Here, we insert data into the sample_numbers table.

Step 3: Using the SQRT() Function

This step involves using the SQRT() function to return the square root of the number column.

SELECT id, number, SQRT(number) AS sqrt_value
FROM sample_numbers;

This query retrieves the id, number, and the square root of the number column for each row in the sample_numbers table. The result will be:

id  number  sqrt_value
--- ------- ----------
1   9       3
2   20.25   4.5
3   144     12
4   0       0

Conclusion

The SQL Server SQRT() function is a powerful tool for returning the square root of a specified number. Understanding how to use the SQRT() function and its syntax is essential for effective mathematical calculations and data processing in SQL Server.