pg.ddx.io  pgsql-general@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Alvaro Herrera <alvherre@2ndquadrant.com>
To: Denisa Cirstescu <Denisa.Cirstescu@tangoe.com>
Cc: pgsql-general@lists.postgresql.org <pgsql-general@lists.postgresql.org>
Subject: Re: Decrease time needed to CREATE INDEX and FOREIGN KEY on new table column which has all values NULL
Date: Tue, 22 Jan 2019 13:47:37 -0300
Message-ID: <201901221647.kce4ahwfygur@alvherre.pgsql> (raw)
In-Reply-To: <MWHPR12MB1664CD85ECAB0420396FF210E6980@MWHPR12MB1664.namprd12.prod.outlook.com>

On 2019-Jan-22, Denisa Cirstescu wrote:

> I am trying to add a new column to a really big table and to define an INDEX and a FOREIGN KEY on that new column using the following instructions:
> 
> ALTER TABLE Employee ADD COLUMN DepartmentId INTEGER;
> CREATE INDEX IDX_Employee_DepartmentId ON Employee(DepartmentId);
> ALTER TABLE Employee ADD CONSTRAINT FK_Employee_Department FOREIGN KEY(DepartmentId) REFERENCES Department(DepartmentId);
> 
> The table is huge and it takes a lot of time to add the INDEX and the FOREIGN KEY although all values are NULL.
> Considering that the new DepartmentId column is NULL for all rows at this point, is there a way to make the INDEX and FOREIGN KEY creation run faster?

The typical advice is to run CREATE INDEX CONCURRENTLY instead of plain
CREATE INDEX.  Also, use "ADD CONSTRAINT ... NOT VALID;" instead, and
later do another ALTER TABLE ... VALIDATE CONSTRAINT.  That decreases
the impact considerably in production scenarios.

-- 
Álvaro Herrera                https://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Remote DBA, Training & Services




view thread (3+ messages)

Message-ID: <201901221647.kce4ahwfygur@alvherre.pgsql>
Permalink:  ../201901221647.kce4ahwfygur@alvherre.pgsql/
Also on:    postgresql.org/message-id/201901221647.kce4ahwfygur@alvherre.pgsql

 · 

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: alvherre@2ndquadrant.com, Denisa.Cirstescu@tangoe.com
  Subject: Re: Decrease time needed to CREATE INDEX and FOREIGN KEY on new table column which has all values NULL
  In-Reply-To: <201901221647.kce4ahwfygur@alvherre.pgsql>
  References: <MWHPR12MB1664CD85ECAB0420396FF210E6980@MWHPR12MB1664.namprd12.prod.outlook.com> <201901221647.kce4ahwfygur@alvherre.pgsql>

* 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