SQL TRY_CONVERT function
TRY_CONVERT(type, value, style) returns NULL when the value cannot convert, so one bad row does not abort a whole INSERT ... SELECT.
- Categoria
- Conversion
- Returns
the target type, or NULL- In this category
- 9 of 39
Sintaxe
TRY_CONVERT(type, expression [, style])
Suporte a mecanismos
| Motor | Support | Notas |
|---|---|---|
| SQL Server | Sim | Supported under this name. |
| PostgreSQL | Not built in | no TRY_CONVERT; test first with pg_input_is_valid (16+) or a regex in CASE |
| MySQL | Not built in | no TRY_CONVERT; CAST errors on unparseable input |
| SQLite | Not built in | no TRY_CONVERT; CAST('x' AS INTEGER) yields 0, a different failure mode |
| Oracle | Not built in | CAST(x AS type DEFAULT NULL ON CONVERSION ERROR) and VALIDATE_CONVERSION, both 12.2+ |
Exemplos
SQL Server
SELECT TRY_CONVERT(DATE, value, 103) AS d FROM staging.imports;
SQL Server
SELECT TRY_CONVERT(INT, phone) AS phone_num FROM customers;
Bom saber
- NULL on failure hides problems: thousands of NULLs after a load usually mean a format mismatch, not missing data. Compare TRY_CONVERT output against the raw column to size the damage.
- The style decides day/month order: TRY_CONVERT(DATE, '13/07/2026', 101) is NULL under US style 101 and 2026-07-13 under British style 103. Worse, '05/07/2026' parses under both styles, as two different dates.
- NULL is only for values that fail to parse. A conversion SQL Server never allows, such as TRY_CONVERT(xml, 4) from int, still raises an error.
Questions about TRY_CONVERT
TRY_CONVERT vs TRY_CAST?
TRY_CAST has no style argument; TRY_CONVERT is CONVERT plus NULL-on-failure. Use TRY_CONVERT when you need a style code, TRY_CAST when you do not.
Why is everything NULL after my import?
Usually a style mismatch or an unexpected format. List the failures with SELECT raw FROM staging WHERE raw IS NOT NULL AND TRY_CONVERT(DATE, raw, 103) IS NULL to see which pattern does not parse.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
- Parse text into a date in SQL Server, PostgreSQL, MySQL, SQLite and Oracle Dialect comparison
- Safe cast that returns NULL instead of an error in SQL Server, PostgreSQL, MySQL, SQLite and Oracle Dialect comparison
Cheat sheets for the engines that have it: SQL Server.
Functions your engine actually has
SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.