Create a SQL Function to Calculate the nth Root of a Number

Vertica has a built-in function to calculate the arithmetic square root a number called SQRT and another built-in function to calculate the arithmetic cube root…

OpenText  profile picture
OpenText

February 27, 20191 min read

Vertica has a built-in function to calculate the arithmetic square root a number called SQRT and another built-in function to calculate the arithmetic cube root of a number called CBRT.

Example:

dbadmin=> SELECT sqrt(9);
sqrt
------
3
(1 row)

dbadmin=> SELECT cbrt(27);
cbrt
------
3
(1 row)

But what if I need a function to calculate the arithmetic nth root of a number? No problem. I can create my own!

dbadmin=> CREATE OR REPLACE FUNCTION nrt (x FLOAT, y FLOAT) RETURN FLOAT
dbadmin-> AS
dbadmin-> BEGIN
dbadmin-> RETURN POWER(x,(1/y));
dbadmin->
dbadmin-> END;
CREATE FUNCTION

dbadmin=> SELECT nrt(390625, 4);
nrt
-----
25
(1 row)

dbadmin=> SELECT nrt(256, 4);
nrt
-----
4
(1 row)

dbadmin=> SELECT nrt(27, 3);
nrt
-----
3
(1 row)

dbadmin=> SELECT nrt(9, 2);
nrt
-----
3
(1 row)

Share this post

Share this post to x. Share to linkedin. Mail to
OpenText avatar image

OpenText

OpenText, The Information Company, enables organizations to gain insight through market-leading information management solutions, powered by OpenText Cloud Editions.

See all posts

More from the author

Are you making the most of your information?

Are you making the most of your information?

Take this quick assessment to find out

May 09, 2025

2 min read

Can CIOs meet today’s challenges and plan for tomorrow?

Can CIOs meet today’s challenges and plan for tomorrow?

Read the new white paper

April 21, 2025

4 min read

From the Great North to global innovation: How OpenText powers the future of tech

From the Great North to global innovation: How OpenText powers the future of tech

The beginning of the year is the perfect time to reflect on one’s successful journey and set our sights on the future. At OpenText, our…

February 28, 2025

3 min read

Stay in the loop!

Get our most popular content delivered monthly to your inbox.