SQL Type Conversion 🎯

beginner
18 min

SQL Type Conversion 🎯

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!

Introduction 📝

Before diving into the conversion techniques, let's understand the basic data types in SQL:

  1. CHAR/VARCHAR: stores character data (strings)
  2. INT/INTEGER: stores integer values (whole numbers)
  3. FLOAT/REAL: stores floating-point values (decimal numbers)
  4. DATE/TIMESTAMP: stores date and time values
  5. BOOLEAN: stores true/false values

Converting Data Types 💡

In SQL, you can convert data types using functions. Here are some common conversion functions:

Converting Char/Varchar to Numeric Types ✅

sql
-- 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 Numeric Types to Char/Varchar ✅

sql
-- 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 ✅

sql
-- 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 ✅

sql
-- Converting BOOLEAN to Char/Varchar CAST(TRUE AS CHAR) -- '1' CAST(FALSE AS CHAR) -- '0'

Converting DATE to TIMESTAMP and Vice Versa ✅

sql
-- 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 and Vice Versa ✅

sql
-- 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)

Practice Time 💡

Quick Quiz
Question 1 of 1

Which function is used to convert an integer to a character in SQL?

Quick Quiz
Question 1 of 1

How would you convert the date '2022-12-01' to a timestamp in SQL?

Quick Quiz
Question 1 of 1

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! 🚀