SQL provides conversion functions that allow you to change a value from one data type to another. This is useful when you need to work with data that might not be in the format you need for specific operations. The two most commonly used conversion functions are CAST and CONVERT. Both functions allow you to convert data types but have some differences in syntax and usage. In this article, we will explore both of these functions with examples.
The CAST function is used to explicitly convert a value from one data type to another. It is part of the ANSI SQL standard and works in most relational database management systems (RDBMS).
CAST(expression AS target_data_type)
CAST takes two arguments: the expression to convert and the target_data_type that you want to convert the expression to. The target_data_type can be any valid SQL data type such as INT, VARCHAR, DATE, etc.
-- Convert a string to an integer SELECT CAST('123' AS INT) AS ConvertedValue;
This query converts the string '123' into an integer value, resulting in 123.
-- Convert a string column to an integer in a table SELECT ProductName, CAST(Price AS INT) AS PriceInt FROM Products;
This query converts the Price column (which might be stored as a string) to an integer for each product in the Products table.
The CONVERT function is similar to CAST, but it is specific to SQL Server and provides additional functionality, such as the ability to format certain data types, like DATETIME. It is not part of the ANSI SQL standard, so it may not work in all database systems.
CONVERT(target_data_type, expression, style)
CONVERT takes three arguments: the target_data_type (the data type you want to convert to), the expression (the value to convert), and an optional style (used for formatting the conversion).
-- Convert a string to an integer SELECT CONVERT(INT, '123') AS ConvertedValue;
This query converts the string '123' into an integer value, similar to the CAST function.
-- Convert a datetime to a string with a specific format SELECT CONVERT(VARCHAR, GETDATE(), 120) AS CurrentDateTime;
This query converts the current date and time into a string format, with the format 'YYYY-MM-DD HH:MI:SS', as defined by the style code 120 in SQL Server.
-- Convert a datetime column to a string in a table SELECT ProductName, CONVERT(VARCHAR, CreatedDate, 103) AS CreatedDateFormatted FROM Products;
This query converts the CreatedDate column (which might be of type DATETIME) to a string in the format 'DD/MM/YYYY', using the style code 103.
Both CAST and CONVERT are useful SQL functions for converting between different data types. The CAST function is part of the ANSI SQL standard and is supported by most RDBMS, while CONVERT is specific to SQL Server and provides additional functionality for formatting date and time values. By using these functions, you can ensure that data is converted to the appropriate type for your queries, making your SQL code more flexible and efficient.