// strings reference

SQL QUOTE_LITERAL function

Returns the argument as a correctly quoted SQL string literal with embedded quotes doubled.

Categoría
Strings
Returns
string
In this category
111 of 172

Sintaxis

quote_literal(string)
quote_nullable(string)

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

Soporte del motor

MotorSupportNotas
SQL Server Different name or syntax QUOTENAME(s, '''') for strings up to 128 characters.
PostgreSQL Sí Supported under this name.
MySQL Different name or syntax Use QUOTE(str).
SQLite Different name or syntax Use QUOTE(x).
Oracle Different name or syntax DBMS_ASSERT.ENQUOTE_LITERAL.

Ejemplos

PostgreSQL

SELECT quote_literal('O''Brien') AS literal;  -- 'O''Brien'

PostgreSQL

SELECT format('SELECT * FROM t WHERE name = %L', 'O''Brien') AS sql;

Conviene saberlo

  • quote_literal(NULL) returns NULL, which silently drops the value from concatenated SQL; quote_nullable(NULL) returns the word NULL. Choose deliberately.
  • Backslashes are doubled and the literal gets an E prefix: quote_literal(E'a\\b') returns E'a\\b', which parses the same whatever standard_conforming_strings is set to.
  • It protects literal values only; identifiers need quote_ident or format's %I.

Questions about QUOTE_LITERAL

When should I use quote_literal instead of %L?

When you are concatenating strings rather than calling format(). Inside format(), %L is shorter and handles NULL like quote_nullable.

Why did my NULL disappear from the generated SQL?

quote_literal(NULL) is NULL, and concatenating NULL makes the whole query string NULL. Use quote_nullable, or format() with %L.

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.