PostgreSQL quote_literal() Function

The PostgreSQL quote_literal() function uses single quotes to quote a given string for using as a string literal in SQL statement strings.

If the string contains single quotes, it will be converted to two single quotes. For example a'b -> 'a''b'.

quote_literal() Syntax

This is the syntax of the PostgreSQL quote_literal() function:

quote_literal(string)

Parameters

string

Required. It can be any type. Non-string values ​​are treated as strings.

Return value

The PostgreSQL quote_literal() function returns an escaped SQL string literal enclosed in single quotes.

If the input is null, this function returns null. So if the arguments might be null, the quote_nullable() function is a better choice.

quote_literal() Examples

Basic usage

This example demonstrates the basic usage of the quote_literal() function.

SELECT
    quote_literal('abc') AS "abc",
    quote_literal('How are you?') AS "How are you?",
    quote_literal(null) AS "null";
``

```output
  abc  |  How are you?  | null
-------+----------------+------
 'abc' | 'How are you?' |

From the above results we can see that:

  1. All strings are enclosed in single quotes.
  2. If the parameter is null, the return value is null.

Embedded single quotes

If the string contains single quotes, each single quote will be converted to two single quotes. For example:

SELECT quote_literal(E'Don\'t do that.');
   quote_literal
-------------------
 'Don''t do that.'

Non-string Parameters

You can use a non-string argument in the quote_literal() function, like:

SELECT quote_literal(123.45);
 quote_nullable
----------------
 '123.45'