What is Difference between CAST vs CONVERT in SQL Server?
What is Difference between CAST vs CONVERT in SQL Server?
1 Answer
In Microsoft SQL Server, both CAST and CONVERT are used to change a value from one data type to another, but they differ in syntax, flexibility, and portability.
1. Basic Syntax
CAST
CAST(expression AS data_type)
Example:
SELECT CAST(123.456 AS INT);
Result:
123
CONVERT
CONVERT(data_type, expression [, style])
Example:
SELECT CONVERT(INT, 123.456);
Result:
123
2. Main Differences
| Feature | CAST | CONVERT |
|---|---|---|
| ANSI SQL Standard | Yes | No (SQL Server-specific) |
| Portability | Better | Less portable |
| Formatting options | Limited | Supports style formatting |
| Readability | More standard | More flexible for dates |
| Extra style parameter | No | Yes |
3. Date Formatting (Biggest Practical Difference)
CONVERT supports a style code, especially useful for formatting dates.
Example:
SELECT CONVERT(VARCHAR, GETDATE(), 103);
Result:
12/05/2026
Here:
103 = British/French date format (dd/mm/yyyy)
Equivalent with CAST:
SELECT CAST(GETDATE() AS VARCHAR);
This gives a default format only — no custom style control.
4. Common Style Codes in CONVERT
| Style | Format |
|---|---|
| 101 | mm/dd/yyyy |
| 102 | yyyy.mm.dd |
| 103 | dd/mm/yyyy |
| 104 | dd.mm.yyyy |
| 120 | yyyy-mm-dd hh:mi:ss |
| 121 | ODBC with milliseconds |
Example:
SELECT CONVERT(VARCHAR, GETDATE(), 120);
5. Performance Difference
In most real-world cases:
- Performance difference is negligible.
- SQL Server optimizes both similarly.
Choose based on:
- readability
- portability
- formatting needs
6. When to Use Which?
Use CAST when:
- Writing portable SQL
- Following ANSI standards
- Simple type conversion is enough
Example:
SELECT CAST(price AS DECIMAL(10,2))
FROM Products;
Use CONVERT when:
- Working specifically in SQL Server
- You need formatted date/time output
- You need style codes
Example:
SELECT CONVERT(VARCHAR(10), OrderDate, 103)
FROM Orders;
7. TRY_CAST and TRY_CONVERT
SQL Server also provides safer versions:
TRY_CAST('abc' AS INT)
Returns:
NULL
instead of throwing an error.
Similarly:
TRY_CONVERT(INT, 'abc')
Very useful for data cleaning and ETL work.
Quick Summary
| Use Case | Recommended |
|---|---|
| Standard SQL | CAST |
| Date formatting | CONVERT |
| Cross-database compatibility | CAST |
| SQL Server-specific formatting | CONVERT |
| Safe conversion | TRY_CAST / TRY_CONVERT |
A common rule developers follow:
Use
CASTby default, and useCONVERTwhen you need formatting styles.