// strings reference

SQL newlines in strings

A newline inside a string literal is engine-specific. The portable route is building it from code points; the fast route is knowing your engine's escape.

Категория
Strings
Returns
string
In this category
71 of 172

Синтаксис

'line1' + CHAR(13) + CHAR(10) + 'line2'
E'line1\nline2'

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.

Примеры

SQL Server

SELECT 'line1' + CHAR(13) + CHAR(10) + 'line2' AS two_lines;

PostgreSQL

SELECT E'line1\nline2' AS two_lines;

Oracle

SELECT 'line1' || CHR(10) || 'line2' AS two_lines FROM dual;

SQLite

SELECT 'line1' || char(10) || 'line2' AS two_lines;

Полезно знать

  • Windows line breaks are two characters (CR + LF): a single CHR(10) or '\n' leaves carriage returns behind in Windows-sourced data.
  • Engine spellings: CHAR(13)+CHAR(10) on SQL Server, CHR(10) on Oracle, char(10) on SQLite, E'\n' on PostgreSQL (plain strings keep the backslash literal), '\n' on MySQL (unless NO_BACKSLASH_ESCAPES).
  • A literal line break typed inside the quotes in your editor is legal SQL on every engine, but it is invisible and fragile in diffs and copy-paste.
  • Strip them again with REPLACE and the same codes; see remove-newlines for the reverse operation.

Questions about Newlines in string literals

What is the most portable way to write a newline?

Build it from code points: CHAR(10) on SQL Server, MySQL and SQLite, CHR(10) on Oracle and PostgreSQL. The function name differs, but the code is the same everywhere.

Why do my newlines show as \n in the output?

You are on PostgreSQL with a plain string: backslash escapes are literal there. Prefix the literal with E, or use chr(10).

Does a real line break inside the quotes work?

Yes. A literal newline inside a string literal is valid on all major engines. It survives execution but tends to get mangled by formatters, diffs and copy-paste.

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

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

// 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.