The forgotten assignment operator “=” and the commonplace “:=”

后端 未结 4 1441
自闭症患者
自闭症患者 2020-11-22 13:23

The documentation for PL/pgSQL says, that declaration and assignment to variables is done with :=. But a simple, shorter and more modern (see foo

4条回答
  •  情话喂你
    2020-11-22 13:47

    In PL/PgSQL parser, assignment operator is defined as

    assign_operator : '='
                    | COLON_EQUALS
                    ;
    

    This is a legacy feature, present in source code since 1998, when it was introduced - as we can see in the PostgreSQL Git repo.

    Starting from version 9.4 it is oficially documented.

    This idiosyncrasy - of having two operators for same thing - was raised on pgsql users list, and some people requested it to be removed, but it's still kept in the core because fair corpus of legacy code relies on it.

    See this message from Tom Lane (core Pg developer).

    So, to answer your questions straight:

    Didn't I find some section in the docs which mention and/or explains this?

    You did not find it because it was undocumented, which is fixed as of version 9.4.

    Are there any known consequences using = instead of :=.

    There are no side consequences of using =, but you should use := for assignment to make your code more readable, and (as a side effect) more compatible with PL/SQL.

    Update: there may be a side consequence in rare scenarios (see Erwin's answer)


    UPDATE: answer updated thanks to input from Daniel, Sandy & others.

提交回复
热议问题