Friday, December 20, 2024

MySQL SQRT() Function

 The SQRT() function in MySQL is used to return the square root of a given number. It takes a single argument, which must be a non-negative number, and returns the square root of that number. If the argument is negative, MySQL will return NULL.

Syntax:

SQRT(number)
  • number: The value for which the square root is calculated. It must be a non-negative number.

Example:

  1. Basic Example:

    SELECT SQRT(16);
    

    Output:

    +----------+
    | SQRT(16) |
    +----------+
    | 4.0000   |
    +----------+
    
  2. Handling Negative Numbers:

    SELECT SQRT(-9);
    

    Output:

    +-----------+
    | SQRT(-9)  |
    +-----------+
    | NULL      |
    +-----------+
    
  3. Using SQRT() with a column in a table:

    SELECT SQRT(price) AS price_sqrt FROM products;
    

    This will return the square root of the price column for each row in the products table.

Notes:

  • The function works only with numbers. If the argument is a string or any non-numeric type, MySQL will attempt to convert it to a number and might return NULL if the conversion fails.
  • The result is returned as a floating-point number, even for whole numbers.

No comments:

Post a Comment