Mastering MySQL Cast: Converting Data Types with Ease
Robert Cooper
Robert Cooper Senior Engineer at Basedash
· January 31, 2025
Robert Cooper
Robert Cooper Senior Engineer at Basedash
· January 31, 2025
Casting in MySQL lets you change a value from one data type to another, ensuring compatibility and proper formatting in your database operations. MySQL’s CAST() and CONVERT() functions are key tools for explicit data type conversion, useful in a range of scenarios from data type mismatches to specific formatting needs.
CAST() function?To change a value’s data type in MySQL, you use the CAST() function. The syntax is fairly straightforward:
CAST(expression AS type)
For converting a string into a date, the command looks like this:
SELECT CAST('2023-01-01' AS DATE);
CONVERT() function?CONVERT(), similar to CAST(), changes a value’s type but also supports additional formatting options. Its syntax goes like:
CONVERT(expression, type)
To convert a datetime to a date string in format YYYY-MM-DD, you would use:
SELECT CONVERT('2023-01-01 12:00:00', DATE);
Casting proves essential when dealing with data type discrepancies. Whether it’s comparing strings with numbers, adjusting data formats before operations, or displaying data in user-specific formats, casting ensures your data aligns with operation requirements and presentation standards.
Here are practical examples illustrating MySQL casting in action:
Converting strings to integers:
SELECT CAST('123' AS UNSIGNED INTEGER);
Changing datetime to date:
SELECT CAST(NOW() AS DATE);
Formatting a number as a decimal:
SELECT CAST(123 AS DECIMAL(10,2));
Casting serves as a crucial feature in MySQL, offering the flexibility needed for precise data type conversion and ensuring operations and outputs adhere to required data standards. It supports maintaining data integrity and enhances the clarity of your results, whether you’re adjusting database schemas, analyzing data, or preparing reports.
Written by
Senior Engineer at Basedash
Robert Cooper is a senior engineer at Basedash who builds full-stack product systems across SQL data infrastructure, APIs, and frontend architecture. His work focuses on application performance, developer velocity, and reliable self-hosted workflows that make data operations easier for teams at scale.
Basedash lets you build charts, dashboards, and reports in seconds using all your data.