Summary: in this tutorial, you will learn how to use the SQL Server SQUARE()
function to calculate the square of a number.
Introduction to the SQL Server SQUARE() function
The SQUARE()
function is a mathematical function that allows you to calculate the square of a number.
Here’s the syntax of the SQUARE()
function:
SQRT(number)
Code language: SQL (Structured Query Language) (sql)
In this syntax:
- The
number
is a float or any number that can be implicitly converted to a float.
The SQUARE()
function returns the square of the number
with the type of float. If the number is NULL
, the SQUARE()
function returns NULL
.
SQL Server SQUARE() function examples
Let’s explore some examples of using the SQUARE()
function.
1) Basic SQUARE() function example
The following statement uses the SQUARE()
function to return the square of 5:
SELECT SQUARE(5) AS result;
Code language: SQL (Structured Query Language) (sql)
Result:
result
------
25
Code language: SQL (Structured Query Language) (sql)
The query returns 25 as the square of 5.
2) Using the SQUARE() function to calculate areas of squares
First, create a table called squares
to store the length of squares:
CREATE TABLE squares(
id INT IDENTITY PRIMARY KEY,
length DEC(10,2)
);
Code language: SQL (Structured Query Language) (sql)
Second, insert some rows into the squares
table:
INSERT INTO squares (length)
VALUES
(2.5),
(3),
(5),
(6),
(9);
Code language: SQL (Structured Query Language) (sql)
Third, retrieve data from the squares
table:
SELECT
id,
length
FROM
squares;
Code language: SQL (Structured Query Language) (sql)
Output:
id | length
---+---------
1 | 2.50
2 | 3.00
3 | 5.00
4 | 6.00
5 | 9.00
(5 rows)
Code language: plaintext (plaintext)
Finally, calculate the areas of the squares using the SQUARE()
function:
SELECT
id,
length,
SQUARE(length) area
FROM
squares;
Code language: SQL (Structured Query Language) (sql)
Output:
id | length | area
---+--------+-------
1 | 2.50 | 6.25
2 | 3.00 | 9.0
3 | 5.00 | 25.0
4 | 6.00 | 36.0
5 | 9.00 | 81.0
(5 rows)
Code language: plaintext (plaintext)
Summary
- Use the SQL Server
SQUARE()
function to calculate the square of a number.