SQL / MySQL
Intermediate
Queries
· 6 min read
SQL CAST and CONVERT
Lesson 26 of 33 in the SQL / MySQL learning path.
How do I compare a numeric string column as a number?
CAST converts a value to another type for the query. It does not alter the column.
A text column sorts 10 before 2. Casting to unsigned sorts them as numbers.
Syntax & Parameters
ORDER BY CAST(seats AS UNSIGNED)
Example
-- Sort a legacy text column numerically for this report only.
SELECT id,
title,
seats
FROM lessons
WHERE seats REGEXP '^[0-9]+$'
ORDER BY CAST(seats AS UNSIGNED),
title;
-- Non-numeric rows are excluded from the report.
-- The seats column is still stored as text.
-- Prefer an integer column when you own the schema.
-- CAST in the SELECT list does not rewrite the table.
Expected Output
Lessons whose seats text is all digits, ordered 2 then 10 then 24, not 10 then 2 then 24.
Line-by-Line Walkthrough
- The WHERE keeps only digit strings.
- CAST seats AS UNSIGNED makes the sort numeric.
- title breaks ties.
- The column type is unchanged.
- Non-numeric rows are left out of this report.
- A bad cast in a WHERE can force a full scan.
- CONVERT is the MySQL spelling with a different argument order.
- The lasting fix is an integer column.
Common Pitfalls & Security
This is easy to misuse.
- CAST in a WHERE often cannot use an index on the text column.
- CAST of an empty string becomes 0 and can look like a real zero.
- Unsigned cast drops a leading minus.
- Sorting with CAST hides the fact that the column type is wrong.
Best Practices & Modern Standards
Cast in a report when you cannot change the table today.
Migrate the column to an integer and stop casting in the hot query.
Real-World Use
An old import stored seats as text. The admin report sorts them numerically until the column is altered.
Frequently Asked Questions
Does CAST change the table?
No. It converts the value for this query only.
Why does 10 come before 2?
Text sort is character by character. Cast to a number to sort by magnitude.
What is CONVERT?
MySQL’s other conversion function. CAST(x AS type) is the form to learn first.
Will an index be used?
Usually not when the indexed column is wrapped in CAST.