PostgreSQL CBRT() Function
Summary: in this tutorial, you will learn how to use the PostgreSQL CBRT()
function to calculate the cube root of a number.
Introduction to the PostgreSQL CBRT() function
A cube root number is a number that when you multiply itself twice, you’ll get the cube number. For example, 2 is a cube root number of 8 because when you multiply the number 2 by itself three times, you’ll get the number 8:
In PostgreSQL, the CBRT()
is a math function that returns the cube root of a number.
Here’s the syntax of the CBRT()
function:
In this syntax:
n
is the number that you want to calculate the cube root.n
can be a literal number, an expression, or a table column.
The CBRT()
function returns the cube root of a number n with the double precision type. If n
is NULL
, the CBRT()
function returns NULL
.
If n
is a string, the CBRT()
function will attempt to convert it to a number before calculating the cube root. If the conversion fails, it raises an error.
PostgreSQL CBRT() function examples
Let’s explore some examples of using the CBRT()
function.
1) Basic PostgreSQL CBRT() function example
The following example uses the CBRT()
function to calculate the cube root of 27:
Output:
It returns 3 because 3* 3 *3 = 27.
2) Using CBRT() function with a negative number
The following example uses the CBRT()
function to find the cube root of -27:
Output:
The result is -3 because -3 * -3 * -3 is -27. Please note that the cube root of a negative number is always negative.
3) Using CBRT() function with numeric strings
The following example uses the CBRT()
function with a numeric string:
Output:
In this example, the CBRT()
function converts the text ‘125’ to the number 125 and calculates the cube root.
4) Using the CBRT() function with table data
First, create a table called cube_volumes
that stores the volumes of cubes:
Second, insert rows into the cube_volumes
table:
Output:
Third, calculate the side lengths of cubes using the CBRT()
function:
Output:
Summary
- Use the
CBRT()
function to calculate the cube root of a number.