SQL CAST and CONVERT: Change Data Types (All Databases)
Convert between data types in SQL with CAST and CONVERT. Covers string to number, date conversions, and type casting across all databases.
Overview
CAST converts a value from one data type to another. It is the SQL standard way to change types and works in every database.
All Databases
-- CAST(expression AS type):
SELECT CAST('123' AS INT); -- 123 (string to integer)
SELECT CAST(123 AS VARCHAR(10)); -- '123' (integer to string)
SELECT CAST('2026-03-12' AS DATE); -- date object
SELECT CAST(99.99 AS INT); -- 99 (truncates decimal)
SELECT CAST(price AS DECIMAL(10,2)) FROM products;
MySQL
-- CAST:
SELECT CAST('123' AS UNSIGNED); -- 123
SELECT CAST('2026-03-12' AS DATE); -- date
SELECT CAST(123 AS CHAR); -- '123'
-- CONVERT (MySQL syntax — different from SQL Server!):
SELECT CONVERT('123', UNSIGNED); -- 123
SELECT CONVERT('abc', BINARY); -- binary
-- Implicit conversion:
SELECT '10' + 5; -- 15 (MySQL auto-converts)
PostgreSQL
-- CAST:
SELECT CAST('123' AS INTEGER); -- 123
SELECT CAST(NOW() AS DATE); -- date only
-- :: shorthand (PostgreSQL only):
SELECT '123'::INTEGER; -- 123
SELECT '2026-03-12'::DATE; -- date
SELECT 99.99::INT; -- 100 (rounds)
SELECT NOW()::DATE; -- today's date
SELECT '{"key": "value"}'::JSONB; -- JSON object
SQL Server
-- CAST:
SELECT CAST('123' AS INT); -- 123
SELECT CAST(GETDATE() AS DATE); -- date only
-- CONVERT(type, expression, style):
SELECT CONVERT(INT, '123'); -- 123
SELECT CONVERT(VARCHAR, GETDATE(), 23); -- '2026-03-12'
-- TRY_CAST / TRY_CONVERT (safe, returns NULL on failure):
SELECT TRY_CAST('abc' AS INT); -- NULL (not an error)
SELECT TRY_CONVERT(DATE, 'not-date'); -- NULL
Skip the Syntax Lookup
Instead of memorizing CAST / CONVERT syntax for each database, describe what you need in plain English and let AI2SQL generate the correct query.
No credit card required
Frequently Asked Questions
How do I convert a string to a number in SQL?
Use CAST('123' AS INT) in all databases. PostgreSQL also supports '123'::INTEGER. SQL Server has TRY_CAST for safe conversion.
What is the difference between CAST and CONVERT?
CAST is SQL standard and works everywhere. CONVERT is database-specific: SQL Server uses CONVERT(type, expr, style) with format codes. MySQL's CONVERT has different syntax.
Can AI2SQL handle type conversions?
Yes. AI2SQL automatically applies correct type casting when generating queries, using the right syntax for your database.