pg.ddx.io  pgsql-general@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Adrian Klaver <adrian.klaver@aklaver.com>
To: André Hänsel <andre@webkr.de>
To: pgsql-general@lists.postgresql.org
Subject: Re: Why is DEFAULT much faster than UPDATE?
Date: Wed, 10 Aug 2022 16:11:11 -0700
Message-ID: <f64728f8-1f12-5f99-262d-4ec71efc13c6@aklaver.com> (raw)
In-Reply-To: <0d4101d8ad0d$3af0cf70$b0d26e50$@webkr.de>
References: <0d4101d8ad0d$3af0cf70$b0d26e50$@webkr.de>

On 8/10/22 16:02, André Hänsel wrote:
> This question is out of curiosity, just to learn more about the internals of
> PostgreSQL.
> 
> The goal was to add a not null bool column filled with "false", but with
> "true" as the default for new rows.
> 
> The naïve approach would be:
> ALTER TABLE foo ADD COLUMN slow bool NOT NULL DEFAULT true;
> UPDATE foo SET slow = false;
> 
> This takes a certain, non-negligible amount of time.
> 
> This on the other hand achieves the same result and is almost instant:
> ALTER TABLE foo ADD COLUMN fast bool NOT NULL DEFAULT false;
> ALTER TABLE foo ALTER COLUMN fast SET DEFAULT true;
> 
> Where does the difference come from, how are those handled internally?

 From here:

https://www.postgresql.org/docs/current/sql-altertable.html

"When a column is added with ADD COLUMN and a non-volatile DEFAULT is 
specified, the default is evaluated at the time of the statement and the 
result stored in the table's metadata. That value will be used for the 
column for all existing rows. If no DEFAULT is specified, NULL is used. 
In neither case is a rewrite of the table required."

> 
> Fiddle:
> https://dbfiddle.uk/?rdbms=postgres_14&fiddle=56595e8ee397a5bc48b84277da3133
> a9
> 
> 
> 


-- 
Adrian Klaver
adrian.klaver@aklaver.com





view thread (2+ messages)

Message-ID: <f64728f8-1f12-5f99-262d-4ec71efc13c6@aklaver.com>
Permalink:  ../f64728f8-1f12-5f99-262d-4ec71efc13c6@aklaver.com/
Also on:    postgresql.org/message-id/f64728f8-1f12-5f99-262d-4ec71efc13c6@aklaver.com

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients from your mail client; the link fills in
  the headers below: reply via email
  Some clients, webmail especially, drop In-Reply-To and References from
  a link, and the reply then starts a new thread: use the mbox below.

  To: pgsql-general@postgresql.org
  Cc: adrian.klaver@aklaver.com, andre@webkr.de
  Subject: Re: Why is DEFAULT much faster than UPDATE?
  In-Reply-To: <f64728f8-1f12-5f99-262d-4ec71efc13c6@aklaver.com>
  References: <0d4101d8ad0d$3af0cf70$b0d26e50$@webkr.de> <f64728f8-1f12-5f99-262d-4ec71efc13c6@aklaver.com>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox