Skip to content

Type Conversion

Sometimes, data is stored in one format but needs to be used in another. For example, a “Price” might be stored as a String (VARCHAR) in a legacy system, but you need it to be a Decimal to perform calculations.

Casting is the process of explicitly converting a value from one data type to another.

The database engine automatically converts a type behind the scenes.

  • Example: If you run SELECT '100' + 5;, the engine might see the string '100', convert it to an integer, and return 105.
  • Danger: Implicit conversion is dialect-dependent and can lead to unexpected errors or slow performance (by preventing index usage).

You tell the database exactly how to convert the data. This is safer and more readable.

The CAST function is supported by almost all major relational databases.

Standard Casting
CAST(expression AS target_type)

PostgreSQL provides a concise syntax for casting.

Postgres Casting
expression::target_type

We have a LegacySales table where everything was stored as text:

IDPriceTextSaleDateText
1’19.99''2023-01-01’
2’5.00''2023-01-02’

Task: Calculate the total price including a 10% tax.

Section titled “Task: Calculate the total price including a 10% tax.”
Casting Examples
SELECT
CAST(PriceText AS DECIMAL(10,2)) * 1.1 AS PriceWithTax,
CAST(SaleDateText AS DATE) AS ValidDate
FROM LegacySales;
PriceWithTaxValidDate
21.9892023-01-01
5.5002023-01-02

Casting is not always safe. You must be aware of the “Capacity” of your data types.

If you cast a DECIMAL(10,5) (which has 5 decimal places) to an INTEGER, the database will truncate the decimal part. 10.99 becomes 10, not 11.

If you try to cast the number 1,000,000 to a SMALLINT (which only goes up to 32,767), the query will fail with an Overflow Error.

Casting the string 'Pizza' to an INTEGER will cause the entire query to crash.

SQL TypeUse Case
INT / INTEGERWhole numbers.
DECIMAL(p,s) / NUMERICExact numbers (Money, Scientific data).
FLOAT / REALApproximate numbers (Large numbers where precision is less critical).
VARCHAR(n)Variable length text.
BOOLEANTrue / False.