SQL cast date to string
Every engine can stringify a date, but the default shape differs wildly (ISO here, locale there), so pick the explicit formatter when it matters.
- カテゴリ
- Dates & times
- Returns
text- In this category
- 96 of 121
構文
CAST(d AS varchar)
d::text
TO_CHAR(d, fmt)
Each block is a separate form. The support table and the examples show which engine takes which.
エンジンサポート
| エンジン | Support | メモ |
|---|---|---|
| SQL Server | はい | CONVERT(varchar, d, style) or FORMAT |
| PostgreSQL | はい | d::text (DateStyle-shaped) or to_char |
| MySQL | はい | CAST(d AS CHAR): ISO 'YYYY-MM-DD hh:mm:ss' |
| SQLite | はい | values are already text; strftime for other shapes |
| Oracle | はい | TO_CHAR(d, fmt); NLS_DATE_FORMAT if implicit |
例
PostgreSQL
SELECT to_char(order_date, 'YYYY-MM-DD') FROM orders;
SQL Server
SELECT CONVERT(varchar(10), order_date, 120) FROM orders;
Oracle
SELECT TO_CHAR(order_date, 'YYYY-MM-DD') FROM orders;
知っておくと便利なこと
- Implicit conversion inherits session settings: PostgreSQL's ::text output changes with DateStyle, Oracle's bare conversion with NLS_DATE_FORMAT. Never build keys or comparisons on implicit shapes.
- ISO output is safe everywhere when asked for explicitly: to_char(d, 'YYYY-MM-DD'), CONVERT(varchar(10), d, 120), DATE_FORMAT(d, '%Y-%m-%d'), strftime('%Y-%m-%d', d).
- SQLite already stores dates as text: 'casting' is a no-op; the work is in strftime masks or keeping the format ISO in the first place.
Questions about Date to text
Why does my date column print differently on two servers?
Session settings: PostgreSQL DateStyle, Oracle NLS_DATE_FORMAT and SQL Server language all alter implicit output. Explicit format masks make output environment-proof.
What is the MySQL default shape?
CAST(datetime AS CHAR) gives 'YYYY-MM-DD hh:mm:ss' whatever the session. Compare SQL Server, where CAST(datetime AS varchar) gives 'Aug 1 2026 2:30PM' (style 0, month name in the session language) while CAST(date AS varchar) gives ISO.
Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.
Related on SQLly
- Format a date as text in SQL Server, PostgreSQL, MySQL, SQLite and Oracle Dialect comparison
- Parse text into a date in SQL Server, PostgreSQL, MySQL, SQLite and Oracle Dialect comparison
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
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.