
For an instructor lead, in-depth look at learning SQL click below.
So, you have dabbled with SQL and need to convert data types for your needs. SQL, Structured Query Language, has built-in functions that allow you to do this quickly and efficiently. Let’s dive into this!
Understanding SQL Data Types
Before we proceed, it is important to understand the various data types in SQL. The commonly used data types are INT (for numerical values without decimal points), DECIMAL or FLOAT (for fractional numbers), VARCHAR (for text), and DATE (for date). Irrespective of the SQL variant you use, these data types will sound familiar.
How to Convert Data Types in SQL?
Now, let’s get to data type conversions. SQL provides a function CAST that allows you to convert an expression to a specific data type.
|
1 2 3 |
SELECT CAST(expression AS datatype) |
Let’s understand this with an example:
Example 1: Convert INT to CHAR
|
1 2 3 |
SELECT CAST(25 AS CHAR); |
This will convert the integer value 25 to a character value ’25’.
Using CONVERT Function
Apart from CAST, SQL Server offers the CONVERT function, which provides additional flexibility. It looks like this:
|
1 2 3 |
SELECT CONVERT(datatype, expression) |
Example 2: Convert DATE to VARCHAR
|
1 2 3 |
SELECT CONVERT(VARCHAR(20), GETDATE(), 103) as 'Date'; |
The above SQL statement converts the current date to a string in dd/mm/yyyy format. ‘103’ is a style code which tells SQL how to format the date.
Conclusion
Conversion of data types in SQL is a common requirement in many real-world scenarios. With the right use of CAST and CONVERT function, you can tackle this issue conveniently. However, always use caution as careless conversions can lead to data loss or errors. Happy coding!
