TRY_CAST in SQL Server converts a value to a specified data type and returns NULL instead of raising an error when the conversion fails. It is the safe counterpart to CAST: same syntax, but a failed conversion becomes a NULL you can test for rather than a query that aborts. You need SQL Server 2012 or later (any edition, including Express) and a query window in SQL Server Management Studio, Azure Data Studio, or any client that can run T-SQL. The steps below use the AdventureWorks sample database, but every example works on any table you can read.

What You'll Need

  • SQL Server 2012 or newer, or Azure SQL Database (TRY_CAST does not exist in SQL Server 2008 and earlier).
  • A client such as SQL Server Management Studio (SSMS) or Azure Data Studio, connected with an account that can run SELECT queries.
  • A table with mixed or dirty data to practise on. The examples use AdventureWorks tables; substitute your own column names.
  • Basic familiarity with SELECT, CAST, and NULL handling. No special permissions beyond read access are required.

Step-by-Step

  1. Confirm your version supports TRY_CAST. Run SELECT SERVERPROPERTY('ProductMajorVersion');. A result of 11 or higher means SQL Server 2012 or later, so TRY_CAST is available. If you get 10 or lower, use CASE with ISNUMERIC or upgrade; TRY_CAST will not parse.
  2. Learn the syntax. The form is TRY_CAST ( expression AS data_type [ (length) ] ). The expression can be a column, a literal, or a calculation. The data type can be any valid SQL Server type, including int, decimal(10,2), date, datetime2, varchar(50), and uniqueidentifier.
  3. See the difference from CAST. Run SELECT CAST('abc' AS int);. It fails with a conversion error and the batch stops. Now run SELECT TRY_CAST('abc' AS int);. It returns NULL. That single behaviour is the whole point: bad data becomes a testable NULL instead of an exception.
  4. Test a successful conversion. Run SELECT TRY_CAST('123' AS int) AS Converted;. The result is 123 as an integer. TRY_CAST returns the converted value whenever the input is valid for the target type.
  5. Apply it to a real column. Suppose a staging table dbo.RawOrders stores OrderDate as nvarchar(30) and some rows contain blanks or text. Run SELECT OrderID, TRY_CAST(OrderDate AS date) AS CleanDate FROM dbo.RawOrders;. Valid dates convert; invalid ones return NULL without breaking the query.
  6. Filter out the failures. Wrap the call in a WHERE clause: SELECT OrderID, TRY_CAST(OrderDate AS date) AS CleanDate FROM dbo.RawOrders WHERE TRY_CAST(OrderDate AS date) IS NOT NULL;. This gives you only rows that converted cleanly, which is the usual pattern for loading a staging table into a typed table.
  7. Count the failures before you load. Run SELECT COUNT(*) AS BadRows FROM dbo.RawOrders WHERE TRY_CAST(OrderDate AS date) IS NULL AND OrderDate IS NOT NULL;. The second condition excludes genuine NULLs so you see only rows that failed conversion. Fix or quarantine those rows before inserting into the target table.
  8. Use it in an INSERT or UPDATE. For example: INSERT INTO dbo.Orders (OrderID, OrderDate) SELECT OrderID, TRY_CAST(OrderDate AS date) FROM dbo.RawOrders WHERE TRY_CAST(OrderDate AS date) IS NOT NULL;. Rows that would have failed are simply skipped, and the statement completes.
  9. Handle dates and decimals carefully. TRY_CAST('2024-13-01' AS date) returns NULL because month 13 is invalid, and TRY_CAST('12.345' AS decimal(5,2)) rounds to 12.35 rather than failing. Style and culture affect string-to-date conversion: use unambiguous formats such as yyyy-MM-dd or yyyyMMdd in your data, because regional settings on the server can change how ambiguous strings like 01/02/2024 are read.
  10. Know when TRY_CAST will not save you. TRY_CAST only catches conversion failures. It does not catch divide-by-zero, overflow in arithmetic performed before the cast, or errors from functions inside the expression. For example, TRY_CAST(1/0 AS int) still raises a divide-by-zero error because the division happens first. Wrap risky arithmetic separately.
  11. Prefer TRY_CAST over TRY_CONVERT when you do not need a style. TRY_CONVERT accepts an optional style argument for date and numeric formatting; TRY_CAST does not. If you need a specific date style, use TRY_CONVERT. Otherwise TRY_CAST is shorter and ANSI-standard in spirit.
  12. Check the result type. TRY_CAST returns NULL of the target type, not of the source type. In a SELECT with UNION or in a computed column, make sure the target type matches what the surrounding query expects, or you may get implicit conversion surprises downstream.

Common Mistakes

  • Assuming TRY_CAST catches every error. It only handles conversion failures. Divide-by-zero, arithmetic overflow, and errors inside functions still raise exceptions.
  • Forgetting that NULL input returns NULL. TRY_CAST(NULL AS int) is NULL, which is correct but can confuse counts. Always distinguish real NULLs from failed conversions by checking the source column too.
  • Using TRY_CAST on the wrong side of a comparison. Writing WHERE TRY_CAST(Col AS int) = 5 prevents index use on Col. If the column is already the right type, cast the literal instead.
  • Ignoring silent rounding. Casting a string with more decimal places than the target precision rounds rather than fails. Check your decimal precision before loading financial data.
  • Relying on ambiguous date strings. Strings like 03/04/2024 can convert differently depending on language and dateformat settings. Use ISO formats in stored data.
  • Using TRY_CAST in SQL Server 2008. It does not exist there; the batch fails with an invalid object name error. Check the version first.

Tips

  • Use TRY_CAST in staging or ETL queries to keep bad rows from aborting a load, then log the NULLs for review.
  • Pair TRY_CAST with ISNULL or COALESCE to substitute a default: ISNULL(TRY_CAST(RawValue AS int), 0).
  • For bulk validation, select the failing rows into a separate table so you can correct them and rerun the load.
  • When converting to date or datetime2, prefer datetime2 for new work because it has a larger range and better precision than the legacy datetime.
  • Remember that TRY_CAST is evaluated row by row; on very large tables, filtering to the rows you need before casting keeps the query fast.

Troubleshooting

  • Error: 'TRY_CAST' is not a recognized built-in function name. You are on SQL Server 2008 or earlier. Check the version with SELECT @@VERSION; and either upgrade or rewrite using CASE with ISNUMERIC or TRY_CONVERT where available.
  • TRY_CAST returns NULL for values you expected to convert. Check for leading or trailing spaces, non-breaking spaces, currency symbols, or commas in numbers. Use LTRIM/RTRIM and REPLACE to clean the string before casting.
  • The query still fails with a conversion error. The error may come from a different expression, such as a JOIN condition or a computed column. Isolate each conversion in its own SELECT to find the culprit.
  • Dates convert differently on another server. Language and dateformat settings differ. Set an explicit style using TRY_CONVERT, or standardise source strings to yyyyMMdd.
  • Performance is slow. Casting a column in WHERE prevents index seeks. If possible, store the data in the correct type at load time, or add a persisted computed column with an index.

Frequently Asked Questions

What is the difference between CAST and TRY_CAST?

CAST raises an error when conversion fails; TRY_CAST returns NULL instead. Both use the same syntax and target types.

Does TRY_CAST work in SQL Server 2008?

No. TRY_CAST was introduced in SQL Server 2012. Use TRY_CONVERT on 2012 and later, or CASE-based checks on older versions.

Can TRY_CAST prevent divide-by-zero errors?

No. TRY_CAST only handles conversion failures. Arithmetic errors such as divide-by-zero still occur and must be handled with NULLIF or CASE.

Why does TRY_CAST return NULL for a number with a comma?

Commas are not valid in numeric strings for implicit or explicit conversion. Remove them with REPLACE before casting.

Is TRY_CAST available in Azure SQL Database?

Yes. Azure SQL Database supports TRY_CAST, as do Azure SQL Managed Instance and SQL Server 2012 and later.

Does TRY_CAST change the data type of the result?

Yes. The result is the target type you specify, or NULL of that type when conversion fails.