Welcome to the SQL Type Conversion tutorial! In this lesson, we'll learn how to convert data between different data types in SQL. This is a crucial skill for any developer, as it allows you to work with various types of data seamlessly. Let's get started!
Before diving into the conversion techniques, let's understand the basic data types in SQL:
In SQL, you can convert data types using functions. Here are some common conversion functions:
-- Converting Char/Varchar to Integer
CAST('25' AS INT) -- 25
CAST('-100' AS INT) -- -100
-- Converting Char/Varchar to Float
CAST('3.14' AS FLOAT) -- 3.14
CAST('0.000001' AS FLOAT) -- 0.000001-- Converting Integer to Char/Varchar
CAST(25 AS CHAR) -- '25'
CAST(-100 AS CHAR) -- '-100'
-- Converting Float to Char/Varchar
CAST(3.14 AS CHAR) -- '3.14'
CAST(0.000001 AS CHAR) -- '0.000001'-- Converting DATE to Char/Varchar
CAST(CURRENT_DATE AS CHAR) -- 'YYYY-MM-DD'
CAST(CURRENT_DATE AS VARCHAR) -- 'YYYY-MM-DD'-- Converting BOOLEAN to Char/Varchar
CAST(TRUE AS CHAR) -- '1'
CAST(FALSE AS CHAR) -- '0'-- Converting DATE to TIMESTAMP
CAST('2022-12-01' AS TIMESTAMP)
-- Converting TIMESTAMP to DATE
DATE(CAST('2022-12-01 12:34:56' AS TIMESTAMP))-- Converting TIMESTAMP to DATETIME
CAST('2022-12-01 12:34:56' AS DATETIME)
-- Converting DATETIME to TIMESTAMP
CAST('2022-12-01 12:34:56' AS TIMESTAMP)Which function is used to convert an integer to a character in SQL?
How would you convert the date '2022-12-01' to a timestamp in SQL?
Which function is used to convert a boolean value to a character in SQL?
That's it for today! In the next lesson, we'll dive deeper into SQL data manipulation and learn about the SQL JOIN operation. Until then, happy coding! 🚀