how to use cast function in postgresql?
CAST function:
In
PostgreSQL, the
CAST function is used to convert a value of one data type to another data type. The basic syntax of the CAST function is as follows:
SQL
CAST (expression AS target_type)
Here, expression is the value that needs to be converted, and target_type is the data type to which the value needs to be converted. The CAST function can be used in a SELECT statement, INSERT statement, UPDATE statement, or any other SQL statement that requires data type conversion.
Let's see some examples of using the CAST function in PostgreSQL:
Example 1: Convert a string to an integer
sql
SELECT CAST('123' AS INTEGER);
Output:
In this example, we are converting the string value '123' to an integer using the CAST function. The output shows that the value has been converted to an integer.
Example 2: Convert a decimal to an integer
sql
SELECT CAST(12.34 AS INTEGER);
Output:
In this example, we are converting the decimal value 12.34 to an integer using the CAST function. The output shows that the value has been converted to an integer by truncating the decimal portion.
Example 3: Convert a timestamp to a date
sql
SELECT CAST('2022-03-14 12:34:56' AS DATE);
Output:
markdown
date
------------
2022-03-14
In this example, we are converting a timestamp value '2022-03-14 12:34:56' to a date using the CAST function. The output shows that the value has been converted to a date by discarding the time portion.
That's how you can
use the CAST function in PostgreSQL to
convert values from one data type to another