SQL Server PI()



SQL Server PI() Function

The SQL Server PI() function returns the value of π (pi), which is approximately 3.14159. This function is useful for mathematical and trigonometric calculations.


Syntax

SELECT PI();

The PI() function does not take any arguments.


Example SQL Server PI() Function Queries

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

1. Basic PI() Example

SELECT PI() AS pi_value;

This query returns the value of π. The result will be:

pi_value
--------
3.141592653589793

2. Using PI() in a Calculation

SELECT PI() * 2 AS circumference_of_unit_circle;

This query calculates the circumference of a unit circle (circle with radius 1) using the formula 2πr. The result will be:

circumference_of_unit_circle
---------------------------
6.283185307179586

3. Using PI() with a Column

SELECT radius, 2 * PI() * radius AS circumference
FROM circles;

This query calculates the circumference of circles stored in the circles table. The result will show the original radius and the calculated circumference for each circle.

4. Using PI() with a Variable

DECLARE @radius FLOAT;
SET @radius = 5;
SELECT 2 * PI() * @radius AS circumference;

This query uses a variable to store a radius value and then calculates the circumference of a circle with that radius. The result will be:

circumference
-------------
31.41592653589793

Full Example

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

Step 1: Creating a Table

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

CREATE TABLE circles (
    id INT PRIMARY KEY,
    radius FLOAT
);

In this example, we create a table named circles with columns for id and radius.

Step 2: Inserting Data into the Table

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

INSERT INTO circles (id, radius) VALUES (1, 1);
INSERT INTO circles (id, radius) VALUES (2, 2.5);
INSERT INTO circles (id, radius) VALUES (3, 4.75);

Here, we insert data into the circles table.

Step 3: Using the PI() Function

This step involves using the PI() function to calculate the circumference of the circles in the circles table.

SELECT id, radius, 2 * PI() * radius AS circumference
FROM circles;

This query retrieves the id, radius, and the calculated circumference for each row in the circles table. The result will be:

id  radius  circumference
--- ------- -------------
1   1       6.283185307179586
2   2.5     15.707963267948966
3   4.75    29.845130209103033

Conclusion

The SQL Server PI() function is a powerful tool for returning the value of π (pi). Understanding how to use the PI() function and its syntax is essential for effective mathematical and trigonometric calculations in SQL Server.