Search code examples
sqlsyntaxlinefeed

What is the standard way of adding carriage returns in line feeds to SQL queries?


What is the standard syntax for adding carriage returns in line feeds to raw SQL queries?


Solution

  • The standard way to insert a carriage return or linefeed into a string literal in a query is to simply include it verbatim within the string literal. There are no escape characters in SQL strings; the only character that can't be included in a string is a single quote (') character, which can be escaped by doubling it.

    For example, to insert a row containing a newline:

    INSERT INTO table VALUES ('this is a string
    with a newline');
    

    If you want to control whether a carriage return, linefeed, or bot will be inserted, you will need to make sure that one or both of them appear in the literal source.

    Some implementations implement C-style escape sequences; in these implementations, you could write '\n', '\r', '\r\n' to add newlines, carriage returns, or CRLFs. However, this syntax is non-standard, so it won't be portable to all databases.