Movatterモバイル変換


[0]ホーム

URL:


Add Neon Auth to your app without leaving Cursor or Claude

PostgreSQL SQRT() Function

Summary: in this tutorial, you will learn how to use the PostgreSQLSQRT() function to calculate the square root of a number.

Introduction to the PostgreSQL SQRT() function

TheSQRT() function is a powerful mathematical function that allows you to calculate the square root of a number.

Here’s the basic syntax of theSQRT() function:

SQRT(number)

In this syntax, thenumber is a numeric value for which you want to calculate the square root

TheSQRT() function returns the square root of the inputnumber.

PostgreSQL SQRT() function examples

Let’s take some examples of using theSQRT() function.

1) Basic SQRT() function example

The following example uses theSQRT() function to return the square root of 25:

SELECT SQRT(25)AS result;

Output:

result--------      5(1 row)

The query returns the square root of 25, which is 5.

2) Using PostgreSQL SQRT() function to calculate distance

Suppose you have a table calledcoordinates that consists of columnsx andy representing the coordinates of points in two-dimensional space:

-- Create coordinates tableCREATE TABLE coordinates (    idSERIAL PRIMARY KEY,    xNUMERIC,    yNUMERIC);-- Insert sample dataINSERT INTO coordinates (x, y)VALUES    (3,4),    (-2,5),    (0,0),    (8,-6),    (-1.5,2.5)RETURNING*;

Output:

id |  x   |  y----+------+-----  1 |    3 |   4  2 |   -2 |   5  3 |    0 |   0  4 |    8 |  -6  5 | -1.5 | 2.5(5 rows)

The following query uses theSQRT() function to calculate the distance of each point from the origin (0,0):

SELECT SQRT(x* x+ y* y)AS distance_from_originFROM coordinates;

Output:

distance_from_origin----------------------    5.000000000000000    5.385164807134504    0.000000000000000   10.000000000000000    2.915475947422650(5 rows)

Summary

  • Use the PostgreSQLSQRT() function to calculate the square root of a number.

Last updated on

Was this page helpful?
Thank you for your feedback!

[8]ページ先頭

©2009-2025 Movatter.jp