SQL Cookbook Lesson

How to calculate a square root in SQL

Learn how to calculate a square root in SQL with examples and explanations from SQLPad.

Problem

You need to calculate the square root of a number in SQL.

Sample Data

We will use a simple table numbers with a single column value containing the following data:

CREATE TABLE numbers (
    value INT
);

INSERT INTO numbers (value)
VALUES (4), (9), (16), (25);

MySQL Solution

SELECT value, SQRT(value) AS square_root
FROM numbers;

PostgreSQL Solution

SELECT value, SQRT(value) AS square_root
FROM numbers;

Explanation

In both MySQL and PostgreSQL, you can calculate the square root of a number using the SQRT function. The usage of the function is the same in both databases. The SQRT function takes one argument, which is the number you want to calculate the square root of.

The SQL query selects all records from the numbers table and calculates the square root of the value field. The result of the square root calculation is returned in a new column named square_root.

Please note that the SQRT function returns a floating-point number. Even if the input is an integer and the square root of the number is a whole number, the result will still be a floating-point number. If you want to get an integer result, you can use the CAST or :: operator to convert the result to an integer.

Keep Practicing

Related Cookbook Lessons

View all lessons

Interview Prep

Begin Your SQL, Python, and R Journey

Master 230 interview-style coding questions and build the data skills needed for analyst, scientist, and engineering roles.