// conversion reference

SQL cast to text

CAST(x AS CHAR) turns a value into text on MySQL, and into a single character on PostgreSQL. The target name, default length and output format all differ per engine.

類別
Conversion
Returns
text
In this category
17 of 39

語法

CAST(expression AS CHAR)  -- MySQL
CAST(expression AS varchar(n))  -- SQL Server, PostgreSQL
CAST(expression AS VARCHAR2(n))  -- Oracle

Each block is a separate form. The support table and the examples show which engine takes which.

引擎支援

引擎Support備註
SQL Server 是 Supported under this name.
PostgreSQL 是 Supported under this name.
MySQL 是 Supported under this name.
SQLite 是 Supported under this name.
Oracle 是 Supported under this name.

範例

MySQL

SELECT CONCAT(id, ' - ', CAST(total AS CHAR)) AS label
FROM orders;

SQLite

SELECT CAST(price AS TEXT) AS p FROM items;

SQL Server

SELECT CONVERT(varchar(19), created_at, 120) AS ts FROM orders;

小知識

  • Target names differ: varchar on SQL Server and PostgreSQL, CHAR on MySQL (which rejects CAST AS VARCHAR), TEXT on SQLite, VARCHAR2(n) on Oracle. On PostgreSQL, CHAR means character(1): CAST(123 AS CHAR) is '1'.
  • Leaving out the length is engine-specific: SQL Server's CAST(x AS varchar) means varchar(30) and errors or cuts beyond that, PostgreSQL's means unlimited, and Oracle's VARCHAR2 without a length is a syntax error.
  • Dates come out in the engine's default format. On SQL Server, CAST(GETDATE() AS varchar(10)) gives 'Nov 20 202' from datetime's style 0; a date column gives '2026-01-31'. Pin it down with CONVERT style 120/126 or TO_CHAR with a mask.

Questions about CAST AS CHAR / VARCHAR

How do I get ISO 8601 dates as text?

SQL Server: CONVERT(varchar(30), d, 126). PostgreSQL: d::date::text or TO_CHAR. MySQL and SQLite store and print ISO by default. Oracle: TO_CHAR(d, 'YYYY-MM-DD').

Why is my number cast losing decimals?

Float-to-text uses the engine's default conversion: SQL Server's CAST(1.0e0/3 AS varchar) is '0.333333', six significant digits. Exact DECIMAL values keep their scale. For floats, format explicitly with CONVERT style 3, TO_CHAR or printf.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.