The SQL SQUARE Function is one of the SQL Mathematical Function which is used to calculate the square of the specified expression or number.
SQL SQUARE Function Syntax
The basic syntax of the SQUARE Function in SQL Server is as shown below:
SELECT SQUARE (Float_Expression) FROM [Source]
In this article we will show you, How to write SQUARE Function in SQL Server with example. For this, We are going to use the below shown data
SQL SQUARE Function Example 1
The SQUARE() Function in SQL is used to calculate the square of a given numeric value. The following query will show multiple ways to use SQUARE function.
DECLARE @i float = 2, @j int = 2.20 SELECT SQUARE(@i) AS [SQL SQUARES] -- Calculating SQUARE directly SELECT SQUARE(3.20) AS [SQL SQUARES] -- Wrong Value SELECT SQUARE(@j) AS [SQL SQUARE] SELECT SQUARE(2.20) AS [SQL SQUARE]
Below lines of code is used to declare float and int variable and assigning the values.
DECLARE @i float = 2, @j int = 2.20
In the below statement, We used SQUARE function to calculate the square of the variable @i. We also assigned new name to that result as ‘SQL Squares’ using SQL ALIAS Column.
SELECT SQUARE(@i) AS [SQL SQUARES]
@i * @i = 2 * 2 = 4
In the next statement, We used the integer value as input for the SQUARE function.
-- Wrong Value SELECT SQUARE(@j) AS [SQL SQUARES] SELECT SQUARE(2.20) AS [SQL SQUARES]
SQUARE (@j) = @j * @j
= 2.20 * 2.20 = 4.84
But we are getting 4 as a result because it is rounding the 2.20 value to 2
NOTE: Please use float variables as a input for SQUARE Function otherwise, you may expect strange results.
SQL SQUARE Function Example 2
Square Function also allows you to calculate the square of column values. In this example, We are going to calculate the square of All the records present in [Sales Amount] using SQUARE Function.
SELECT [EnglishProductName] ,[Color] ,[StandardCost] ,[SalesAmount] ,SQUARE([SalesAmount]) AS Sales FROM [Mathemetical Functions]
Thank You for Visiting Our Blog