CAST / CONVERT
Overview
CAST / CONVERT β Change a Value from One Data Type to Another
Beginners usually need these when:
- A number is stored as text
- A date is stored as text
- You need to format a number
- You want to compare two columns with different data types
These functions help prevent errors and make data easier to work with.
What CAST Does
CAST changes a value into a new data type.
CAST(value AS new_type)
Example idea:
CAST('123' AS INT)β 123CAST(3.75 AS INT)β 3
What CONVERT Does
CONVERT does the same thing as
CAST, but uses a different format.
CONVERT(new_type, value)
Both are fine for beginners β they do the same job.
Examples
Example 1: Convert credits (number) to text
SELECT course_name,
CAST(credits AS CHAR) AS CreditsText
FROM courses;
Explanation
- Turns a number into text
- Useful when combining text and numbers in one column
Example 2: Convert student_id (number) to text
SELECT first_name,
last_name,
CONVERT(CHAR, student_id) AS StudentIDText
FROM students;
Explanation
- Makes the ID a text value
- Helpful when joining with systems where IDs are stored as strings
Example 3: Convert grade to a decimal
SELECT student_id,
course_id,
CAST(grade AS DECIMAL(5,2)) AS GradeDecimal
FROM enrollments;
Explanation
- Ensures grades always show two decimal places
- Useful for reports and calculations
Example 4: Convert a text date into a real date
SELECT CAST('2024-09-01' AS DATE) AS CleanDate;
Explanation
- Turns a text string into a real date
- Allows use of date functions like
DATEDIFForDATEADD
Why CAST / CONVERT Are Useful
- Fix data stored in the wrong data type
- Make comparisons accurate
- Prepare data for calculations
- Clean up messy imports
Beginners often hit data type mismatch errors β these functions solve that problem.
CAST / CONVERT Summary
| Function | Purpose | Beginner Explanation |
|---|---|---|
CAST |
Change a value to a new type | βTurn this into that.β |
CONVERT |
Same as CAST, different syntax | βUse this type for the value.β |
Practice Tasks (Your Turn!)
Task 1
Convert credits to text.
Task 2
Convert student_id to text.
Task 3
Convert grade to a decimal
with two decimal places.
Select a Task
Click a task from Practice Tasks to begin.
Click a task from Practice Tasks to begin.
Results will appear here…

