Ad space (banner)
🗄️SQL Lessons
Lesson 47 / 50

Converting Types with CAST

This lesson covers converting data types with CAST, so a number stored as text can actually be used in a calculation. It's for anyone searching "SQL CAST tutorial."

CAST(value AS type) converts between types — string to number, number to string, and so on — necessary whenever you need to compute with a number that's actually stored as text.

The example converts a text column price_text to a number with CAST(price_text AS INTEGER), then doubles it. Skip the CAST and try the calculation directly on the raw text, and you'll see an unexpected result or an outright error.

A common early mistake is not anticipating what happens when the text can't actually be converted — depending on the database, that might raise an error or silently produce something unexpected like 0, so it's worth checking the data's format is actually valid beforehand. Data imported from a CSV file often stores what should be numeric values as plain text, so casting types before you calculate with them is a standard step to get right.

SQL
OUTPUT

💡 The SQL engine may take a few seconds to load the first time you run code.

Ad space (banner)
Ad space (in-article)