TRY_CONVERT is SQL Server's safe conversion function: it attempts to convert a value to a target data type and returns NULL instead of raising an error when the conversion fails. Use it when you are cleaning imported data, validating user input, or joining tables where the data types do not line up and you cannot afford a query to abort on a single bad row. The syntax is TRY_CONVERT(data_type, expression [, style]), and it behaves like CONVERT except that it never throws a conversion error for invalid values.

What You'll Need

  • Access to a SQL Server instance (any reasonably current version supports TRY_CONVERT) and a tool such as SQL Server Management Studio, Azure Data Studio, or sqlcmd.
  • Permission to run SELECT statements against the database and table you want to test.
  • A sample table or literal values that include both valid and invalid data, so you can see the NULL behavior in action.
  • Basic familiarity with SQL Server data types (int, decimal, date, datetime, varchar, and so on).

Step-by-Step

  1. Start with a simple literal test. Run SELECT TRY_CONVERT(int, '123') AS Result; and confirm you get 123. Then run SELECT TRY_CONVERT(int, 'abc') AS Result; and confirm you get NULL rather than an error. This is the core difference from CONVERT.
  2. Compare it with CONVERT on the same bad value. Run SELECT CONVERT(int, 'abc'); in a separate query window. It raises a conversion error and the batch stops. Seeing both side by side makes it clear when TRY_CONVERT is the right tool.
  3. Apply it to a real column. Suppose a staging table has a varchar column called AmountText that should hold numbers. Query it with SELECT AmountText, TRY_CONVERT(decimal(18,2), AmountText) AS Amount FROM Staging;. Rows with clean numbers return a value; rows with text, blanks, or malformed numbers return NULL.
  4. Find the rows that failed. Filter with WHERE TRY_CONVERT(decimal(18,2), AmountText) IS NULL AND AmountText IS NOT NULL. This gives you a list of problem records to fix before loading them into a typed column. Excluding NULL source values keeps genuine nulls out of your error list.
  5. Use the style argument for dates and times. TRY_CONVERT accepts the same style codes as CONVERT. For example, TRY_CONVERT(date, '31/12/2024', 103) interprets the string as dd/mm/yyyy and returns a date; without the style code it may return NULL depending on language settings. Common codes include 101 (mm/dd/yyyy), 103 (dd/mm/yyyy), 112 (yyyymmdd), and 120 (yyyy-mm-dd hh:mi:ss).
  6. Use it in a CASE expression when you need a fallback. Write CASE WHEN TRY_CONVERT(int, RawValue) IS NULL THEN 0 ELSE TRY_CONVERT(int, RawValue) END to replace bad values with a default. Be aware the expression is evaluated more than once, so for expensive conversions consider a CTE or a derived table that computes the converted value once.
  7. Test the target type carefully. TRY_CONVERT returns NULL not only for malformed text but also for values that overflow the target type. TRY_CONVERT(tinyint, '300') returns NULL because 300 does not fit in a tinyint. Check your target type's range before assuming a NULL means the text was non-numeric.
  8. Move cleaned data into a typed column. Once you have filtered or defaulted the bad rows, insert the converted values into the destination table, for example INSERT INTO Clean (Amount) SELECT TRY_CONVERT(decimal(18,2), AmountText) FROM Staging WHERE TRY_CONVERT(decimal(18,2), AmountText) IS NOT NULL;. Review the row counts before and after to confirm nothing was silently dropped.

Common Mistakes

  • Assuming NULL means "not a number." A NULL result can also mean the value overflowed the target type, or the source value was already NULL. Always check the source column for NULLs separately.
  • Forgetting the style code for regional dates. Strings like '03/04/2024' are ambiguous. Without a style code, the result depends on the session's language and dateformat settings, so the same query can behave differently on another server.
  • Using TRY_CONVERT to hide data quality problems. Returning NULL quietly is convenient, but if you never inspect the failed rows, bad data silently disappears from reports. Pair TRY_CONVERT with a query that lists the failures.
  • Expecting TRY_CONVERT to catch every error. It handles conversion failures, not things like division by zero or invalid object names. Those still raise errors.
  • Using it where the target type is already correct. Converting an int column to int adds no safety and can prevent index usage in some predicates. Apply it to the text side of comparisons, not the typed side.

Tips

  • Use TRY_CONVERT in WHERE clauses to filter out bad rows before a join or insert, rather than converting after the fact.
  • For large staging tables, compute the converted value once in a CTE and reuse it, so the conversion is not repeated for every reference.
  • Keep a small "rejects" table where you insert rows that returned NULL, along with the reason, so you can review and correct them later.
  • Remember TRY_CONVERT is available in SQL Server and Azure SQL Database; if you also work with other database engines, check whether they offer an equivalent before copying queries across.
  • When converting to date or datetime, prefer unambiguous formats such as yyyymmdd (style 112) for data you control, which avoids language-setting surprises.

Troubleshooting

If TRY_CONVERT returns NULL for values you believe are valid, check three things in order. First, look at the raw value for hidden characters: leading or trailing spaces, non-breaking spaces, or commas used as thousands separators will all cause a failure. Use LEN and a hex dump to inspect suspicious rows. Second, confirm the target type can hold the value; a number that is too large for the type returns NULL even though the text is numeric. Third, check the style code for dates: a mismatch between the string format and the style code produces NULL.

If your query is slow after adding TRY_CONVERT, the conversion likely prevents an index seek on the column. Rewrite the predicate so the typed column remains unmodified, or persist the converted value in a computed column and index that instead. If results differ between servers, compare the language and dateformat settings of each session, since those affect implicit date parsing.

Frequently Asked Questions

What is the difference between TRY_CONVERT and CONVERT?

CONVERT raises an error when a conversion fails and stops the statement. TRY_CONVERT returns NULL instead, letting the rest of the query continue. Both accept the same target type, expression, and optional style arguments.

Does TRY_CONVERT work with dates?

Yes. It supports the same style codes as CONVERT, so you can parse regional date strings such as dd/mm/yyyy by passing style 103. Without a style code, parsing depends on session language settings.

Why does TRY_CONVERT return NULL for a number that looks valid?

The most common causes are hidden characters or spaces in the text, a value that overflows the target type, or a date string that does not match the style code. Inspect the raw value and the target type's range.

Can I use TRY_CONVERT in a WHERE clause?

Yes, and it is a common pattern for filtering out bad rows. Be aware that applying it to a column can prevent index usage, so test performance on large tables.

Is TRY_CONVERT available in all SQL Server versions?

It was introduced in SQL Server 2012 and is available in later versions and Azure SQL Database. Very old versions do not support it, so check your version if a query fails with an invalid function name error.

What happens if the source value is NULL?

TRY_CONVERT returns NULL for a NULL input, just as CONVERT does. That means a NULL result does not always indicate a failed conversion, so check the source column separately when auditing data.