← Back to Chapters

MySQL DECIMAL, CAST & CONVERT

? MySQL DECIMAL, CAST & CONVERT

? Quick Overview

MySQL provides DECIMAL, CAST(), and CONVERT() to accurately handle numeric values and safely convert data between different types. These features are critical when working with prices, calculations, and formatted data.

? Key Concepts

  • DECIMAL Stores exact fixed-point numbers
  • CAST() Converts values using SQL standard syntax
  • CONVERT() MySQL-specific type conversion
  • Prevents floating-point precision errors

? Syntax / Theory

DECIMAL is commonly used for financial values where accuracy matters. CAST and CONVERT are used to change one data type into another during queries.

? View Code Example
-- DECIMAL datatype syntax
DECIMAL(total_digits, decimal_places)

-- CAST syntax
CAST(expression AS datatype)

-- CONVERT syntax
CONVERT(expression, datatype)

? Code Example(s)

? View Code Example
-- Creating a table using DECIMAL for price
CREATE TABLE products (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50),
price DECIMAL(10,2)
);
? View Code Example
-- Casting a string value to DECIMAL
SELECT CAST('123.45' AS DECIMAL(5,2)) AS converted_price;
? View Code Example
-- Converting integer to DECIMAL using CONVERT
SELECT CONVERT(100, DECIMAL(6,2)) AS decimal_value;

? Live Output / Explanation

The DECIMAL datatype stores numbers exactly as defined. CAST() and CONVERT() change the data type at runtime without modifying table structure. This is useful in calculations, reports, and formatted output.

? Interactive Demo: Precision Simulator

Enter a raw number and choose how many decimal places to cast it to.

Result: 123.46

✅ Tips & Best Practices

  • Use DECIMAL instead of FLOAT for money values
  • Always specify precision and scale clearly
  • Prefer CAST for SQL-standard compatibility
  • Use CONVERT for MySQL-specific formatting

? Try It Yourself

  • Create a table with salary stored as DECIMAL
  • Convert string numbers into DECIMAL
  • Compare FLOAT vs DECIMAL results
  • Use CAST in SELECT calculations