Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't a COMMENT string in Postgres be concatenated?

Tags:

postgresql

I tried to concatenate a longer comment over several lines to keep my code clean and was surprised to find that I can't. For example, the following returns a syntax error at the pipes:

COMMENT ON VIEW my_view IS 'foo' || 'bar';

Is there something special about comments?

like image 483
maciej Avatar asked Dec 11 '19 03:12

maciej


People also ask

How do you add a comment in PostgreSQL?

Syntax Using /* and */ symbols In PostgreSQL, a comment that starts with /* symbol and ends with */ and can be anywhere in your SQL statement. This method of commenting can span several lines within your SQL.

What does || mean in PostgreSQL?

The PostgreSQL concatenate operator ( || ) is used to concatenate two or more strings and non strings.

How do I concatenate columns in PostgreSQL?

PostgreSQL allows you to directly concatenate strings, columns and int values using || operator. Here is the SQL query to concatenate columns first_name and last_name using || operator. You can even concatenate string with int using || operator.


Video Answer


2 Answers

The documentation explains about the argument:

The new comment, written as a string literal; or NULL to drop the comment.

So you cannot have an expression in that place, only a constant.

Fortunately the SQL standard has decreed that adjacent string literals be concatenated, so you can write

COMMENT ON VIEW my_view IS 'foo'
   'bar';
like image 177
Laurenz Albe Avatar answered Sep 28 '22 22:09

Laurenz Albe


The documentation states that only text and no expressions are allowed:

COMMENT ON { ACCESS METHOD object_name | ... VIEW object_name } IS 'text'

Note the apos around text. But you may use dynamic created statements for that:

DO $$                      
BEGIN
    EXECUTE FORMAT('COMMENT ON VIEW myview IS %L', 'A very long ' || 'comment');
END
$$ LANGUAGE PLPGSQL;
like image 38
clemens Avatar answered Sep 28 '22 22:09

clemens