SQL CAST Function: How to Convert Data Types in SQL

DbVisualizerDbVisualizer
2 min read

Need to convert data types in SQL? Whether you're formatting strings, handling math, or cleaning up query results, the CAST function is the standard tool. It's supported by most major databases and helps you explicitly control how data behaves.

Key Examples

String to INT

SELECT CAST('123' AS INT);

Float to Integer

SELECT CAST(42.69 AS SIGNED);

Integer to Decimal

SELECT CAST(3 AS DECIMAL);

String to Date

SELECT CAST('2024-12-21' AS DATE);

INT to String

SELECT CAST(42 AS CHAR);

Best Practices

  • Use CAST for readable, portable queries.

  • Only cast when necessary—avoid performance overhead.

  • Use native date functions when formatting is needed.

  • Validate inputs to avoid unexpected NULLs or errors.

FAQ

Is CAST available everywhere?

Yes, in MySQL, PostgreSQL, SQL Server, Oracle, and others.

Is CAST the same as CONVERT?

They both convert types, but CAST is more portable.

Can I cast to any type?

Only to supported target types—check your DB’s docs.

What happens with an invalid cast?

You’ll get NULL or an error depending on the system.

Conclusion

The SQL CAST function is a reliable way to convert values between types. From strings to numbers, or dates to text, it’s essential for clean, safe queries. Want a smoother workflow? Use tools like DbVisualizer to visually inspect and cast data on the fly. Read SQL CAST Function: Everything You Need to Know article for more insights.

0
Subscribe to my newsletter

Read articles from DbVisualizer directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

DbVisualizer
DbVisualizer

DbVisualizer is the database client with the highest user satisfaction. It is used for development, analytics, maintenance, and more, by database professionals all over the world. It connects to all popular databases and runs on Win, macOS & Linux.