Casting in PostgreSQL: Handling Data Type Conversions Effectively
Tags: cast, postgres
Published: 2024-01-18 08:00:00

Let’s explore the CAST PostgreSQL function, take a look at what it is, what it does, its pros and cons, and when to use it.
---
Tools used in this tutorial
[DbVisualizer](https://www.dbvis.com/download/), top rated database management tool and SQL client.
The [PostgreSQL](https://www.postgresql.org/) database

---
Casting types is a crucial aspect of managing data in any application. Without proper data type conversion, you may have unexpected results or even errors that can be hard to detect. That's where the `CAST` function in Postgres comes into play!

In this article, you will discover the ins and outs of the `CAST` function in Postgres and learn how to use it effectively to convert data types.

## What Is CAST in PostgreSQL?
`CAST` is a PostgreSQL function that defines how to convert data types. In cases where data needs to be converted from one type to another, casting allows you to achieve this seamlessly.

The syntaxes below illustrate the operation of CAST in PostgreSQL:

(A) Using the CAST() Function

```
CAST ( expression AS target_data_type );
```

In the syntax above, you first specify an expression that can be a constant, a table column, or an expression that evaluates to a value, and then you specify the target data type to which you want to convert the result of the expression.

(B) Using the :: Operator

```
expression::target_data_type
```

The :: operator allows you to cast an expression directly to the specified target data type. The expression can be a column name, a literal value, or the result of a calculation. Both syntaxes, however, produce the same results.

## How to Use CAST in PostgreSQL
In the general syntax, the "expression" parameter represents the value that you want to convert, and the "data_type" parameter represents the target data type that you want to convert the value to.

For example, let's say you have a table called "employees" with a column called "salary" that contains decimal values. If you want to convert the "salary" values to integers, you can use the CAST function in a SQL query like this:

```
SELECT CAST(salary AS INTEGER) AS salary_int 
FROM employees;
```

Here, the `CAST` function is used to convert the "salary" values to integers, and the resulting column is named "salary_int" in the result set.

## Pros and Cons of CAST

### Pros

- **Flexibility:** PostgreSQL provides a wide range of casting functions, which gives developers a lot of flexibility to convert data between different formats.
- **Query Optimization:** Casting can also be used in the optimization of queries by converting data types to suit the expected data types of indexes or functions used in the query.

### Cons

- **Data Loss:** Casting can lead to data loss if the conversion is not done correctly. For example, converting a floating-point number to an integer will truncate the decimal portion of the number, resulting in data loss.
- **Performance:** Casting can come with a performance downside if it's used extensively within your queries or if your database is not optimized for high performance.

## PostgreSQL CASTING: Use Cases

### (1) Casting a String to an Integer
Provided that there’s a string ‘069’ that is needed to be converted into an integer, we can use the `CAST` function to do this as shown below:
<br />
![Casting a String to an Integer.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ijzq6euu3s0wvejlbql1.png)
<figure><figcaption>Casting a String to an Integer.</figcaption></figure>
<br />

This query will return the integer value 069. The `CAST` function takes the string '069' as its input and converts it to an integer data type. Let’s note that the resulting integer value can be stored in an integer column in a table.
<br />
![Successful Conversion of String to Integer Data Type.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/74rtszqlcpfx30q99ytz.png)
<figure><figcaption>Successful Conversion of String to Integer Data Type.</figcaption></figure>
<br />
It is important to bear in mind that if the expression or input string cannot be converted to the target data type, PostgreSQL will throw an error and so it’s always critical to ensure that the input data, before casting it to the target data type, is validated.

### (2) Casting a String to a Double
Let's say we have a string '11.8' that we want to convert to a double. We can use the CAST function to do this as shown here:
<br />
![DOUBLE Data Type Error in PostgreSQL.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q9vwg2i6vnty417g7wpr.png)
<figure><figcaption>DOUBLE Data Type Error in PostgreSQL.</figcaption></figure>
<br />
You realize that there’s an error. This is because the `DOUBLE` data type is not recognized by PostgreSQL as it is not a standard SQL data type and isn’t part of the SQL standard that PostgreSQL follows.

To fix this, you need to use `DOUBLE PRECISION` instead of `DOUBLE` as shown here in [DbVisualizer](https://www.dbvis.com/eval/):

![Rectification of Error with the DOUBLE PRECISION Data Type.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oconknqxlll2yocnkofv.png)
<figure><figcaption>Rectification of Error with the DOUBLE PRECISION Data Type.</figcaption></figure>
<br />

### (3) Casting a Table Data
Let's assume we have a table called "orders" with columns "order_id", "order_date", and "total_cost". The "order_date" column is of type `text`, and we want to convert it to a `date` data type using the `CAST` function in a SELECT query as shown below:

```
SELECT order_id, CAST(order_date AS DATE), total_cost
FROM orders;
```

When the query is executed, the "order_date" column will contain date values instead of text values.

You could also use `CAST` with table data in this instance: first, create a table called **players** that consists of two columns, and then insert some data into the **players** table with the query below:
<br />
![Creating and Inserting Data into a Table.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bj9l8a2jwofj5vnfx3tm.png)
<figure><figcaption>Creating and Inserting Data into a Table.</figcaption></figure>
<br />
Because the requirements change, let us use the same players table to store ratings as numbers e.g., `1`, `2`, `3` instead of `A`, `B`, and `C` so that players table stores mixed values including numeric and string data types with the following query:

```
INSERT INTO players (rating)
VALUES
	(1),
	(2),
	(3);
```
To know if our modifications have worked, let us run this query in the SQL commander of DbVisualizer:
<br />
![Running Query in DbVisualizer.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qtgz2tayns0zi50whoce.png)
<figure><figcaption>Running Query in DbVisualizer.</figcaption></figure>
<br />
Great! Everything is on point. Now, let us do this exercise by converting all values in the rating column into integers. When we do this, the `A`, `B`, and `C` ratings will be displayed as zero. 

To do this, let us build a query that retrieves data from the players table and includes a `CASE` statement that checks the value of the rating column and returns a different value if the value is a string that can be converted to an integer or not.
<br />
![Converting Values in the ‘Rating’ Column into Integers.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g323aksoa98b0wtrrw82.png)
<figure><figcaption>Converting Values in the ‘Rating’ Column into Integers.</figcaption></figure>
<br />
The query above uses a `CASE` statement with a regex pattern to conditionally convert the **rating** column values to integers and returns a default value of **0** for non-numeric values.

## Conclusion
In this article, you learned that CAST is a powerful tool for effectively converting data types from one form to another. 

To better appreciate its capabilities, you need a tool that helps you manage databases and visually explore query results. This is where a full-featured database client like DbVisualizer comes in. In addition to being able to connect to several DBMSs, it offers advanced query optimization functionality, and full support for all PostgreSQL features, including CAST. [Download DbVisualizer for free now!](https://www.dbvis.com/download/)

## FAQs

### What is PostgreSQL CAST?
PostgreSQL CAST is a function that is used to convert a value of one data type to another data type, such as converting a string to a date.

### How do I use PostgreSQL CAST?
To use PostgreSQL `CAST`, you can include the `CAST` function in your SQL query, followed by the value you want to convert and the target data type enclosed in parentheses.

### What should I do if PostgreSQL CAST fails to convert my data?
It may be because the source data isn’t in a format that can be converted to the target data type. When this happens, you may need to transform the data before re-attempting the conversion process.


## About the author
Leslie Gyamfi is a mobile/web app developer with a passion for creating innovative solutions. He is dedicated to delivering high-quality products and technical articles. You can connect with him on [LinkedIn](https://www.linkedin.com/in/lesliegyamfi/).