1

I have seen the double dollar sign ($$) being used often in FUNCTION declarations and while doing declare statements. I acknowledge that it is probably some syntax related feature, but I am not too clear how/why to use it and when.

Code examples of usage below:

CREATE OR REPLACE FUNCTION BuildFunction(IN prefix TEXT, IN func_id INTEGER) RETURNS BOOLEAN AS $$
BEGIN
...
END; $$

Point of confusion, how do you return a boolean as a $$, is it some special type or something?

DO $$
DECLARE  
   a integer := 10;  
   b integer := 20;  
   c integer;  
BEGIN  
   c := a + b;
    RAISE NOTICE'Value of c: %', c;
END $$;

This code snippet is from How do you use variables in a simple PostgreSQL script?

mu is too short
  • 426,620
  • 70
  • 833
  • 800
PoorProgrammer
  • 459
  • 1
  • 4
  • 14
  • I think this question is already asked on SO, Please check https://stackoverflow.com/questions/31285366/what-does-the-mean-in-postgresql-function – Tajinder Jul 23 '19 at 18:16

1 Answers1

1

From the fine manual:

4.1.2.4. Dollar-Quoted String Constants

While the standard syntax for specifying string constants is usually convenient, it can be difficult to understand when the desired string contains many single quotes or backslashes, since each of those must be doubled. To allow more readable queries in such situations, PostgreSQL provides another way, called “dollar quoting”, to write string constants. A dollar-quoted string constant consists of a dollar sign ($), an optional “tag” of zero or more characters, another dollar sign, an arbitrary sequence of characters that makes up the string content, a dollar sign, the same tag that began this dollar quote, and a dollar sign.

The dollar quoting is a PostgreSQL-specific way of quoting strings that will contain a lot of internal single quotes without forcing you to escape quotes and make an unreadable mess. So these are equivalent string literals:

'R''hllor'
$$R'hllor$$

Dollar-quoting isn't specific to functions, you can use it for any string literals, but it is most commonly seen in function definitions as in your two examples.

mu is too short
  • 426,620
  • 70
  • 833
  • 800