SQL Server SQUARE()


SQL Server SQUARE() Function

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


Syntax

SELECT SQUARE(number);

The SQUARE() function takes a single argument:

  • number: The number to be squared.

Example SQL Server SQUARE() Function Queries

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

1. Basic SQUARE() Example

SELECT SQUARE(4) AS result;

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

result
------
16

2. SQUARE() with a Decimal Number

SELECT SQUARE(5.5) AS result;

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

result
------
30.25

3. SQUARE() with a Column

SELECT number, SQUARE(number) AS square_value
FROM sample_numbers;

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

4. SQUARE() with a Variable

DECLARE @num FLOAT;
SET @num = 12.3;
SELECT SQUARE(@num) AS result;

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

result
------
151.29

Full Example

Let's go through a complete example that includes creating a table, inserting data, and using the SQUARE() 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, 4);
INSERT INTO sample_numbers (id, number) VALUES (2, 5.5);
INSERT INTO sample_numbers (id, number) VALUES (3, 12.3);
INSERT INTO sample_numbers (id, number) VALUES (4, 7);

Here, we insert data into the sample_numbers table.

Step 3: Using the SQUARE() Function

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

SELECT id, number, SQUARE(number) AS square_value
FROM sample_numbers;

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

id  number  square_value
--- ------- ------------
1   4       16
2   5.5     30.25
3   12.3    151.29
4   7       49

Conclusion

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