To convert an INT column or literal value to VARCHAR in SQL Server (T-SQL), use CAST(expression AS VARCHAR(length)) (ANSI standard, portable across SQL engines) or CONVERT(VARCHAR(length), expression) (T-SQL specific). Always specify an explicit length—such as VARCHAR(12) or VARCHAR(20)—rather than bare VARCHAR, which defaults to a very short length in some contexts and can silently truncate values.
- Standard T-SQL Conversion: CAST and CONVERT Both CAST and CONVERT handle standard integer-to-string conversions cleanly when given a sufficient length:
SQL – Using CAST (ANSI standard) SELECT order_id, CAST(order_id AS VARCHAR(20)) AS order_id_str, ‘ORD-’ + CAST(order_id AS VARCHAR(20)) AS order_code FROM dbo.orders;
– Using CONVERT (T-SQL) SELECT order_id, CONVERT(VARCHAR(20), order_id) AS order_id_str, CONCAT(‘ORD-’, CONVERT(VARCHAR(20), order_id)) AS order_code FROM dbo.orders; A 32-bit INT ranges from -2,147,483,648 to 2,147,483,647 (up to 11 characters including the sign); BIGINT can reach 20 characters (-9223372036854775808 to 9223372036854775807). Size VARCHAR(n) accordingly.
- Why Explicit Length Matters (VARCHAR(20) vs. Bare VARCHAR) In T-SQL, using VARCHAR without a length in variable declarations, CAST, or CONVERT can default to length 1 or 30 depending on the statement context:
SQL DECLARE @num INT = 123456;
– Safe: explicit length holds all digits SELECT CAST(@num AS VARCHAR(12)) AS full_value; – ‘123456’
– Avoid bare VARCHAR without length; always specify size explicitly If a converted string exceeds the declared VARCHAR(n) length, SQL Server truncates the string (or raises an error depending on setting/context), leading to silent data corruption in keys or codes.
- Handling NULLs and String Concatenation NULL propagation: CAST(NULL AS VARCHAR(20)) and CONVERT(VARCHAR(20), NULL) return NULL.
Concatenation safety: In T-SQL, ‘Prefix-’ + CAST(col AS VARCHAR(20)) evaluates to NULL if col is NULL, whereas CONCAT(‘Prefix-’, col) implicitly converts non-null values and treats NULL as an empty string ‘’.
SQL – Returns NULL if customer_id is NULL SELECT ‘CUST-’ + CAST(customer_id AS VARCHAR(20)) AS plus_concat FROM dbo.customers;
– Returns ‘CUST-’ if customer_id is NULL SELECT CONCAT(‘CUST-’, customer_id) AS concat_fn FROM dbo.customers; 4. Operational Checklist Always specify a VARCHAR(n) length (for example, VARCHAR(12) for INT or VARCHAR(20) for BIGINT) to prevent truncation.
Prefer CAST(… AS VARCHAR(n)) for cross-dialect readability in reference queries, or CONVERT(VARCHAR(n), …) when matching existing T-SQL conventions.
Avoid casting indexed INT columns to VARCHAR inside WHERE or JOIN predicates—doing so makes the predicate non-SARGable and forces implicit conversions or index scans.
Use NVARCHAR(n) instead of VARCHAR(n) if the resulting string will be combined with Unicode (N’…') literals or stored in NVARCHAR columns.
