Search code examples
postgresqlcolumn-defaults

Postgres: how does a default value get populated?


To be clear, I want to know what is the mechanism that is used to populate the default value not the SQL syntax needed to create the default value constraint on the table.

Does Postgres use some kind of trigger that updates the default value if it is missing or something else?. I couldn't find an explanation on the official website.


Solution

  • This happens in the rewriteTargetListIU function in src/backend/rewrite/rewriteHandler.c. The comment says it all:

    /*
     * rewriteTargetListIU - rewrite INSERT/UPDATE targetlist into standard form
     *
     * This has the following responsibilities:
     *
     * 1. For an INSERT, add tlist entries to compute default values for any
     * attributes that have defaults and are not assigned to in the given tlist.
     * (We do not insert anything for default-less attributes, however.  The
     * planner will later insert NULLs for them, but there's no reason to slow
     * down rewriter processing with extra tlist nodes.)  Also, for both INSERT
     * and UPDATE, replace explicit DEFAULT specifications with column default
     * expressions.
    

    So this happens during query rewrite, which is the step between parsing the SQL string and optimizing it.