Skip to main content
Documents
Basic SyntaxMath FunctionsDate FunctionsJSON FunctionsDatabasesTables & Schema ManagementString FunctionsTriggersIndexes

PostgreSQL -

PostgreSQL provides a comprehensive set of mathematical functions that allow users to perform arithmetic operations and complex calculations directly within their queries. These functions are essential for manipulating numerical data, performing statistical analysis, and optimizing query results.

Usage
Math functions in PostgreSQL are used to execute mathematical operations on data stored in your database. They can be utilized in SELECT statements, WHERE clauses, and other SQL commands to perform calculations instantly, without pre-computation.

SELECT function_name(argument1, argument2, ...)
FROM table_name;

In this syntax, function_name is replaced with the specific mathematical function you wish to execute, such as ABS, ROUND, or POWER, applied to the specified arguments.

Examples

1. Absolute Value

SELECT ABS(-15);

This example uses the ABS function to return the absolute value of -15, resulting in 15.

2. Round a Number

SELECT ROUND(123.4567, 2);

Here, the ROUND function rounds the number 123.4567 to two decimal places, producing 123.46.

3. Power Function

SELECT POWER(2, 3);

The POWER function calculates 2 raised to the power of 3, resulting in 8.

4. Ceiling Function

SELECT CEIL(4.2);

The CEIL function rounds the number 4.2 up to the nearest whole number, resulting in 5.

5. Floor Function

SELECT FLOOR(4.8);

The FLOOR function rounds the number 4.8 down to the nearest whole number, resulting in 4.

6. Square Root Function

SELECT SQRT(16);

The SQRT function returns the square root of 16, resulting in 4.

7. Modulo Function

SELECT MOD(10, 3);

The MOD function returns the remainder of 10 divided by 3, resulting in 1.

8. Handling NULL Values

SELECT COALESCE(NULL, 0) + 5;

Using COALESCE, this example substitutes NULL with 0, resulting in 5.

Tips and Best Practices

  • Choose the right function. Use the most appropriate mathematical function for your calculation to ensure accuracy and efficiency.
  • Consider performance. Be mindful of the computational cost, especially when applying functions to large datasets.
  • Handle nulls carefully. Anticipate and manage NULL values in your data to prevent unexpected results, using functions like COALESCE or NULLIF.
  • Use precision wisely. When dealing with decimal numbers, specify precision to avoid rounding errors.
  • Combine functions for complex calculations. You can nest functions to perform more sophisticated mathematical operations within a single query.

Data Type Compatibility
Mathematical functions in PostgreSQL are compatible with numeric data types, such as INTEGER, NUMERIC, REAL, and DOUBLE PRECISION. Ensure your data is in a suitable format to avoid type conversion errors.