📜  postrgres trunc - SQL (1)

📅  最后修改于: 2023-12-03 15:03:50.451000             🧑  作者: Mango

PostgreSQL TRUNC

Introduction

In PostgreSQL, the TRUNC function is used to truncate a number to a specified precision. The precision is specified as an integer, which determines the number of decimal places to truncate to. TRUNC returns the integer value and discards the decimal places. In addition to the integer values, TRUNC can also be used with timestamp and interval values.

Syntax

The basic syntax of the TRUNC function is as follows:

TRUNC(number, precision)

Where:

  • number: the number to be truncated.
  • precision: the number of decimal places to truncate to.
Examples
Example 1:
SELECT TRUNC(123.456, 2);

Output:

123.45

In this example, the number 123.456 is truncated to 2 decimal places.

Example 2:
SELECT TRUNC(456.789, -1);

Output:

450

In this example, the number 456.789 is truncated to the nearest tens place.

Example 3:
SELECT TRUNC(TIMESTAMP '2021-01-01 12:50:30.123456', 'hour');

Output:

2021-01-01 12:00:00

In this example, the timestamp value is truncated to the hour.

Example 4:
SELECT TRUNC(INTERVAL '2 days 12:00:00', 'day');

Output:

2 days

In this example, the interval value is truncated to the day.

Conclusion

The TRUNC function in PostgreSQL is a powerful tool for truncating numeric, timestamp, and interval values to a specified precision. By specifying the precision, you can control the level of detail in the output, and ensure that the values are consistent across your application.