MySQL - SQRT() Function



MySQL SQRT() function accepts a non-negative number as a parameter, calculates the square root of the given value and returns the result. Simply, this function is used to display the square root of the given value.

When a number is multiplied by itself, the product obtained is the square of that number. This process is known as squaring. And, a square root is defined as the inverse of squaring.

Syntax

Following is the syntax of MySQL SQRT() function −

SQRT(x);

Parameters

This function takes a non-negative numeric value as a parameter.

Return Value

This function returns the square root of the given value.

Example

The following example uses the MySQL SQRT() function to calculate the square root of the number 144 −

SELECT SQRT(144) As Result;

Output

The output for the query above is produced as given below −

Result
12

Example

We can also pass the number as a string value to this function −

SELECT SQRT('625') As Result;

Output

This will produce the following result −

Result
25

Example

If the argument passed to this function is a negative value, the resultant value will be NULL −

SELECT SQRT(-2254) As Result;

Output

This will produce the following result −

Result
NULL

Example

In the following example, we are creating a table named CUSTOMERS using the CREATE statement as follows −

CREATE TABLE CUSTOMERS (
   ID INT AUTO_INCREMENT,
   NAME VARCHAR(20) NOT NULL,
   AGE INT NOT NULL,
   ADDRESS CHAR (25),
   SALARY DECIMAL (18, 2),
   PRIMARY KEY (ID)
);

The below query adds 7 records into the above created table −

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES 
(1, 'Ramesh', 32, 'Ahmedabad', 2000.00 ),
(2, 'Khilan', 25, 'Delhi', 1500.00 ),
(3, 'Kaushik', 23, 'Kota', 2000.00 ),
(4, 'Chaitali', 25, 'Mumbai', 6500.00 ),
(5, 'Hardik', 27, 'Bhopal', 8500.00 ),
(6, 'Komal', 22, 'Hyderabad', 4500.00 ),
(7, 'Muffy', 24, 'Indore', 10000.00 );

To verify whether the records are inserted, execute the following query −

Select * From CUSTOMERS;

Following is the CUSTOMERS table −

ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 Kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 Hyderabad 4500.00
7 Muffy 24 Indore 10000.00

Now, we are using the MySQL SQRT() function to calculate square root of all the values in SALARY column −

SELECT *, SQRT(SALARY) As SQRT FROM CUSTOMERS;

The output for the query above is produced as given below −

ID NAME AGE ADDRESS SALARY SQRT
1 Ramesh 32 Ahmedabad 2000.00 44.721359549995796
2 Khilan 25 Delhi 1500.00 38.72983346207417
3 Kaushik 23 Kota 2000.00 44.721359549995796
4 Chaitali 25 Mumbai 6500.00 80.62257748298549
5 Hardik 27 Bhopal 8500.00 92.19544457292888
6 Komal 22 Hyderabad 4500.00 67.08203932499369
7 Muffy 24 Indore 10000.00 100
Advertisements