SQL Tutorial › Functions & Grouping › CAST & CONVERT

SQL CAST and CONVERT

IntermediateLesson 30 of 698 min read7 queries run on MySQL 8.4

Sometimes a value has the wrong type for the job: numbers stored as text, dates arriving as strings, an average that needs fixed decimals. CAST and CONVERT change the type of a value inside a query. Knowing them also explains the strange results MySQL’s automatic conversion can produce.

Advertisement
In this lesson
  • Convert values with CAST(x AS type) and CONVERT(x, type)
  • Turn text into numbers and dates, and back
  • Control precision with DECIMAL(p,s)
  • Spot implicit conversion surprises

CAST syntax

MySQL
CAST(expression AS type)CONVERT(expression, type)

The target types MySQL accepts in CAST are: SIGNED, UNSIGNED, DECIMAL(p,s), DOUBLE, FLOAT, CHAR, DATE, TIME, DATETIME, YEAR, BINARY and JSON. Note: INT and VARCHAR are not valid targets in MySQL; use SIGNED and CHAR.

Text to number

MySQL
SELECT CAST('42' AS SIGNED)            AS to_int,       CAST('19.99' AS DECIMAL(6,2))   AS to_decimal,       CAST('3.7' AS SIGNED)           AS truncated_int,       '10' + 5                        AS implicit;
ResultMySQL 8.4
to_intto_decimaltruncated_intimplicit
4219.99315
1 row in set
How this query works, step by step
  1. CAST('42' AS SIGNED) turns the text into the integer 42.
  2. DECIMAL(6,2) keeps two decimals.
  3. Casting the text '3.7' to an integer reads digits up to the . and gives 3, with a “truncated incorrect value” warning. (Casting the number 3.7, without quotes, rounds to 4.)
  4. '10' + 5 shows implicit conversion: MySQL silently converts the text for arithmetic and returns 15.
Advertisement

Sorting numbers stored as text

A common bug: codes stored in a VARCHAR sort alphabetically, so '10' comes before '9':

SQL
CREATE TABLE tickets (ticket_no VARCHAR(10));INSERT INTO tickets VALUES ('9'), ('10'), ('2'), ('100');SELECT ticket_no FROM tickets ORDER BY ticket_no;SELECT ticket_no FROM tickets ORDER BY CAST(ticket_no AS UNSIGNED);
ResultMySQL 8.4
mysql> CREATE TABLE tickets (ticket_no VARCHAR(10))
Query OK, 0 rows affected
mysql> INSERT INTO tickets VALUES ('9'), ('10'), ('2'), ('100')
Query OK, 4 rows affected
mysql> SELECT ticket_no FROM tickets ORDER BY ticket_no
ticket_no
10
100
2
9
4 rows in set
mysql> SELECT ticket_no FROM tickets ORDER BY CAST(ticket_no AS UNSIGNED)
ticket_no
2
9
10
100
4 rows in set
How this query works, step by step
  1. The first sort compares text character by character: '1' < '2' < '9', so 10 and 100 come first.
  2. Casting to UNSIGNED sorts by numeric value: 2, 9, 10, 100.
  3. The real fix is to store numbers in a numeric column.

Number to text

MySQL
SELECT emp_id,       CAST(emp_id AS CHAR)                      AS id_text,       CONCAT('EMP-', emp_id)                    AS implicit_text,       CHAR_LENGTH(CAST(salary AS CHAR))         AS salary_digitsFROM employeesLIMIT 3;
ResultMySQL 8.4
emp_idid_textimplicit_textsalary_digits
100100EMP-1006
101101EMP-1016
102102EMP-1025
3 rows in set

CONCAT converts numbers to text automatically, so an explicit CAST is rarely needed there.

Advertisement

Text to date

MySQL
SELECT CAST('2026-01-31' AS DATE)                       AS iso_text,       CAST('2026-01-31 18:30:00' AS DATETIME)          AS with_time,       CAST('2026-01-31 18:30:00' AS DATE)              AS date_only,       STR_TO_DATE('31-01-2026', '%d-%m-%Y')            AS other_format;
ResultMySQL 8.4
iso_textwith_timedate_onlyother_format
2026-01-312026-01-31 18:30:002026-01-312026-01-31
1 row in set
How this query works, step by step
  1. CAST(... AS DATE) understands the ISO format YYYY-MM-DD.
  2. Casting a datetime to DATE drops the time.
  3. For any other layout use STR_TO_DATE with a format string (Date Functions).

DECIMAL for fixed precision

MySQL
SELECT dept_id,       AVG(salary)                      AS raw_avg,       CAST(AVG(salary) AS DECIMAL(10,2)) AS avg_2dpFROM employeesWHERE dept_id IN (1, 2)GROUP BY dept_id;
ResultMySQL 8.4
dept_idraw_avgavg_2dp
178400.000078400.00
269000.000069000.00
2 rows in set
Advertisement

CONVERT and character sets

CONVERT(x, type) is MySQL’s alternative syntax for CAST. CONVERT(x USING charset) converts between character sets:

MySQL
SELECT CONVERT('123', SIGNED) AS same_as_cast,       CHARSET(CONVERT('café' USING latin1)) AS latin1_charset;
ResultMySQL 8.4
same_as_castlatin1_charset
123latin1
1 row in set

Implicit conversion surprises

When you compare text with a number, MySQL converts the text to a number. Text that does not start with digits becomes 0:

MySQL
SELECT 'abc' = 0     AS text_equals_zero,       '12abc' = 12  AS leading_digits,       '1e3' = 1000  AS scientific;
ResultMySQL 8.4
text_equals_zeroleading_digitsscientific
111
1 row in set
How this query works, step by step
  1. 'abc' becomes 0, so 'abc' = 0 is true (1), with a warning.
  2. '12abc' becomes 12.
  3. '1e3' is read as scientific notation, 1000.
Watch out

Comparing a VARCHAR column with a number (for example WHERE phone = 9845012345) converts every row’s value, cannot use an index, and can match unexpected rows. Compare text columns with quoted text.

Quick quiz

1. Which CAST is valid in MySQL?

2. What does SELECT '10' + 5 return in MySQL?

3. Why do the text values ’10’, ‘9’, ‘100’ sort as ’10’, ‘100’, ‘9’?

Advertisement

CAST and CONVERT FAQ

What is the difference between CAST and CONVERT in MySQL?

CAST(x AS type) is standard SQL. CONVERT(x, type) does the same in MySQL, and CONVERT(x USING charset) also converts character sets.

How do I convert a string to a number in MySQL?

Use CAST(text AS SIGNED), CAST(text AS UNSIGNED) or CAST(text AS DECIMAL(p,s)). Adding 0 (text + 0) also works through implicit conversion.

How do I convert a string to a date in SQL?

CAST('2026-01-31' AS DATE) works for ISO dates. For other formats use STR_TO_DATE(text, format).

Why can’t I CAST to INT in MySQL?

MySQL’s CAST accepts SIGNED [INTEGER] and UNSIGNED [INTEGER] as integer targets, not INT. (MySQL 8.0.17 and later also accept CAST(x AS FLOAT) and DOUBLE.)