---
title: try_cast function
description: Learn the syntax of the try\_cast function of the SQL language in Databricks SQL and Databricks Runtime.
canonical_url: https://docs.databricks.com/aws/en/sql/language-manual/functions/try_cast
---

# `try_cast` function

**Applies to:** ![check marked yes](https://docs.databricks.com/aws/en/images/icons/check.png) Databricks SQL ![check marked yes](https://docs.databricks.com/aws/en/images/icons/check.png) Databricks Runtime 10.4 LTS and above

Returns the value of `sourceExpr` cast to the `targetType` if the cast is supported; otherwise, it returns `NULL`, provided that the cast from the type of `sourceExpr` to `targetType` is supported. If the source and target types are not a valid cast combination, a `DATATYPE_MISMATCH` error is returned. See [Returns](https://docs.databricks.com/aws/en/sql/language-manual/functions/cast.md#returns) for supported cast combinations.

## Syntax

```
try_cast(sourceExpr AS targetType)
```

## Arguments

* `sourceExpr`: Any castable expression.
* `targetType`: The type of the result.

## Returns

The result is of type `targetType`.

This function is a more relaxed variant of [`cast` function](https://docs.databricks.com/aws/en/sql/language-manual/functions/cast.md) which includes a detailed description.

`try_cast` differs from [`cast` function](https://docs.databricks.com/aws/en/sql/language-manual/functions/cast.md) by tolerating the following conditions as long as the cast from the type of `expr` to `type` is supported:

* If a `sourceExpr` value cannot fit within the domain of `targetType` the result is `NULL` instead of an overflow error. Casts to DECFLOAT follow the exception below.
* If a `sourceExpr` value is not well formed or contains invalid characters the result is `NULL` instead of an invalid data error.

Exceptions to the above are:

* Casting to [DECFLOAT](https://docs.databricks.com/aws/en/sql/language-manual/data-types/decfloat-type.md) uses `DECFLOAT_ROUNDING_MODE`. With the default `ROUND_HALF_EVEN`, overflow produces signed infinity rather than `NULL`. Rounding to the target precision can also succeed without returning `NULL`.
* Casting to a [STRUCT](https://docs.databricks.com/aws/en/sql/language-manual/data-types/struct-type.md) field with `NOT NULL` property.
* Casting a [MAP](https://docs.databricks.com/aws/en/sql/language-manual/data-types/map-type.md) key.

## Examples

```sql
> SELECT try_cast('10' AS INT);
 10

> SELECT try_cast('a' AS INT);
 NULL
```

## Related functions

* [`::` (colon colon sign) operator](https://docs.databricks.com/aws/en/sql/language-manual/functions/coloncolonsign.md)
* [`cast` function](https://docs.databricks.com/aws/en/sql/language-manual/functions/cast.md)
