Search code examples
sqlpostgresqldollar-quoting

What is `AS $$` in sql functions?


CREATE FUNCTION one() RETURNS integer AS $$
    SELECT 1 AS result;
$$ LANGUAGE SQL;

why i cant write like this:

CREATE FUNCTION one() RETURNS integer
    SELECT 1 AS result;
  • what is AS $$?
  • what is $$ LANGUAGE SQL?
  • what is $$?

Solution

  • In PostgreSQL it is a feature called dollar-quoting, which allows you to include a body of text without escaping the single quotes

    Using it as

    CREATE OR REPLACE FUNCTION hello_world(param_your_name text)
    RETURNS text AS
    $$
    SELECT 'Hello world. My name is ' || param_your_name || '.';
    $$
    language sql STRICT;
    

    which is easier to read than

    CREATE OR REPLACE FUNCTION hello_world(param_your_name text)
    RETURNS text AS
    '
    SELECT ''Hello world. My name is '' || param_your_name || ''.'';
    '
    language sql STRICT;
    

    Read more here - https://www.postgresonline.com/journal/archives/376-Dollar-quoting-for-escaping-single-quotes.html