![]() |
VOOZH | about |
The PostgreSQL CAST function provides an efficient way to convert data types in PostgreSQL, which is important when ensuring data is in the correct format for storage, calculations, or comparisons.
In PostgreSQL, we can use CAST to transform data between various data types, such as converting strings to integers, dates, or booleans. This article will guide you through the PostgreSQL CAST syntax, examples of its usage, and important considerations.
In PostgreSQL, the CAST function is a flexibleoperator that allows us to change the data type of an expression to a target data type. This function is essential in situations where the data type of a value must match the requirements of an operation or a query.
Syntax
CAST ( expression AS target_type );Key Terms
Let us take a look at some of the examples of CAST Operator in PostgreSQL to better understand the concept.
The following statement converts a string constant to an integer:
Query:
SELECT
CAST ('100' AS INTEGER);
Output
π psql castIf the expression cannot be converted to the target type, PostgreSQL will raise an error. See the following:
SELECT
CAST ('10C' AS INTEGER);
Error Output
This will result to the below-depicted error:
π PostgreSQL CAST Operator ExampleThe following example demonstrates how to convert a string to a date format in PostgreSQL:
Query:
SELECT
CAST ('2020-01-01' AS DATE),
CAST ('01-OCT-2020' AS DATE);
Output
π PostgreSQL CAST Operator ExampleExplanation:
The result will be the date values '2020-01-01' and '2020-10-01', respectively.
In PostgreSQL, we can also use CAST to convert string values like 'true', 'T', 'false', and 'F' to boolean values. Hereβs an example:
Query:
SELECT
CAST('true' AS BOOLEAN),
CAST('false' as BOOLEAN),
CAST('T' as BOOLEAN),
CAST('F' as BOOLEAN);
Output
π PostgreSQL CAST Operator ExampleExplanation:
The result will be 'true', 'false', 'true', and 'false', respectively.
::) in PostgreSQLIn PostgreSQL, we have two ways to perform type casting:
CAST(expression AS target_type))::): PostgreSQL's shorthand notation (expression::target_type)SELECT '100'::INTEGER;Output:
| INTEGER |
|---|
| 100 |
Explanation:
This cast operator achieves the same result as CAST ('100' AS INTEGER) but with a simplified syntax.
The PostgreSQL CAST function is an essential tool for data type conversion, providing a reliable way to transform data between formats like string to integer, date, or boolean. Whether you use the CAST function or the cast operator (::), these conversions improve data accuracy and streamlinePostgreSQL queries. Keep in mind that incompatible conversions will raise errors, so always ensure data compatibility for seamless operations.