Beginner

694. JOIN with CAST

Use CAST to convert data types when JOIN columns have incompatible formats.

📘 Lesson 694 of 728 ⏱ 15 min 🎯 Advanced

CAST explicitly converts a value from one data type to another so it can participate in a compatible comparison.

Data from different systems may store the same business key using different data types.

Match a numeric customer ID with a character-based customer ID.

SQL
SELECT
    c.CustomerName,
    r.RiskCategory
FROM Customers c
INNER JOIN RiskRecords r
    ON CAST(c.CustomerID AS VARCHAR(20)) = r.CustomerID;

Used in data integration, migrations, legacy systems, and cross-system reporting.

  • CAST explicitly converts data types.
  • It can resolve incompatible JOIN columns.
  • Conversion can introduce errors if values are invalid.
  • Functions on JOIN columns may affect index usage.
  • Standardizing data types at the schema level is usually better.
Why use CAST in a JOIN?

CAST can convert different data types so related values can be compared.

Can CAST affect JOIN performance?

Yes. Applying a conversion to an indexed column can sometimes prevent efficient index usage.

Have you finished this lesson?

Introduction to SQL – All Lessons