40.2. Handling of Quotations Marks

Since the code of any procedural language function is specified CREATE FUNCTION as a string literal, single quotes inside the function body must be escaped. This can lead to rather complicated code at times, especially if you are writing a function that generates other functions, as in the example in Section 40.6.4. The list below gives you an overview over the needed levels of quotation marks in various situations. Keep this chart handy.

1 quotation mark

To begin/end function bodies, for example:

CREATE FUNCTION foo() RETURNS integer AS '...'
    LANGUAGE plpgsql;

2 quotation marks

For string literals inside the function body, for example:

a_output := ''Blah'';
SELECT * FROM users WHERE f_name=''foobar'';

The second line is interpreted as

SELECT * FROM users WHERE f_name='foobar';

4 quotation marks

When you need a single quote in a string inside the function body, for example:

a_output := a_output || '' AND name LIKE ''''foobar'''' AND xyz''

The value of a_output would then be: AND name LIKE 'foobar' AND xyz.

6 quotation marks

When a single quote in a string inside the function body is adjacent to the end of that string constant, for example:

a_output := a_output || '' AND name LIKE ''''foobar''''''

The value of a_output would then be: AND name LIKE 'foobar'.

10 quotation marks

When you want two single quotes in a string constant (which accounts for 8 quotes) and this is adjacent to the end of that string constant (2 more). You will probably only need that if you are writing a function that generates other functions. For example:

a_output := a_output || '' if v_'' || 
    referrer_keys.kind || '' like '''''''''' 
    || referrer_keys.key_string || '''''''''' 
    then return ''''''  || referrer_keys.referrer_type 
    || ''''''; end if;''; 

The value of a_output would then be:

if v_... like ''...'' then return ''...''; end if;