<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Andrew Pan</title>
    <description>The latest articles on DEV Community by Andrew Pan (@andrewpsy).</description>
    <link>https://dev.to/andrewpsy</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3389457%2F7f74db64-7a0f-477f-bcc6-d36f9d307614.jpg</url>
      <title>DEV Community: Andrew Pan</title>
      <link>https://dev.to/andrewpsy</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/andrewpsy"/>
    <language>en</language>
    <item>
      <title>PostgreSQL SET NOT NULL Zero Downtime Gotcha</title>
      <dc:creator>Andrew Pan</dc:creator>
      <pubDate>Mon, 28 Jul 2025 01:30:43 +0000</pubDate>
      <link>https://dev.to/andrewpsy/the-set-not-null-downtime-trap-in-postgresql-1o71</link>
      <guid>https://dev.to/andrewpsy/the-set-not-null-downtime-trap-in-postgresql-1o71</guid>
      <description>&lt;p&gt;It's necessary to validate existing data before changing a column to "not null." The validation requires an "Access Exclusive" lock which blocks all access to the table, i.e. not only prevents &lt;code&gt;insert&lt;/code&gt;/&lt;code&gt;update&lt;/code&gt;/&lt;code&gt;delete&lt;/code&gt; but also blocks &lt;code&gt;select&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;The duration of the access exclusive lock depends on the table size. In order to support such schema migrations without extended downtime, PostgreSQL version 12 introduced an optimization: when altering a column to "not null" the table scan validation step can be skipped if there exists a valid constraint can prove the column is indeed "not null" at runtime.&lt;br&gt;
Here is a process to set a column to "not null" without downtime:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;create a check constraint but don't initiate validation (no table scan if &lt;code&gt;NOT VALID&lt;/code&gt; is specified):

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;ALTER TABLE users ADD CONSTRAINT email_not_null_chk CHECK (email IS NOT NULL) NOT VALID;&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;validate the "not null" constraint:

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;ALTER TABLE users VALIDATE CONSTRAINT email_not_null_chk;&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;set column "not null" when the constraint is validated successfully

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;ALTER TABLE users ALTER COLUMN email SET NOT NULL;&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;This process doesn't require a downtime because "validate constraint" (2nd step) requires a much less restrictive lock &lt;code&gt;SHARE UPDATE EXCLUSIVE&lt;/code&gt;. The lock is compatible with &lt;code&gt;ROW EXCLUSIVE&lt;/code&gt;, required by insert/update/delete, so normal database operations are not blocked by the check constraint validation. The "set not null" step finds a valid check constraint that proves the column can't be null so table scan is skipped, hence the optimization.&lt;/p&gt;

&lt;p&gt;Now the column is "NOT NULL" so the constraint &lt;code&gt;email_not_null_chk&lt;/code&gt; should be dropped.&lt;/p&gt;

&lt;p&gt;DO NOT &lt;code&gt;ALTER TABLE users ALTER COLUMN email SET NOT NULL, DROP CONSTRAINT IF EXISTS email_not_null_chk;&lt;/code&gt;!!!&lt;br&gt;
It's not unreasonable to assume the drop will occur when "set not null" is done. However PostgreSQL performs &lt;code&gt;DROP CONSTRAINT&lt;/code&gt; before &lt;code&gt;SET NOT NULL&lt;/code&gt; therefore the optimization introduced in version 12 will not happen because by the time the execution flow reaches &lt;code&gt;SET NOT NULL&lt;/code&gt; the constraint is already gone. A full table scan will start to confirm no records violate the &lt;code&gt;not null&lt;/code&gt; column constraint. Suddenly a seemingly harmless milliseconds metadata only schema update blocks every access to the table.&lt;/p&gt;

&lt;p&gt;Official manual can't document every scenario but this can be confirmed in source code:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;AlterTable &lt;a href="https://github.com/postgres/postgres/blob/master/src/backend/commands/tablecmds.c#L4523" rel="noopener noreferrer"&gt;entry point&lt;/a&gt; that calls ATController to &lt;a href="https://github.com/postgres/postgres/blob/master/src/backend/commands/tablecmds.c#L4859" rel="noopener noreferrer"&gt;manage execution flow&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;after phase 1 (which validated user SQL statement and constructed pending tasks, i.e. wqueue), phase 2 &lt;a href="https://github.com/postgres/postgres/blob/master/src/backend/commands/tablecmds.c#L5303" rel="noopener noreferrer"&gt;iterates&lt;/a&gt; from &lt;a href="https://github.com/postgres/postgres/blob/master/src/backend/commands/tablecmds.c#L151-L163" rel="noopener noreferrer"&gt;0 to 11&lt;/a&gt; to execute tasks in that order, we can see &lt;code&gt;drop&lt;/code&gt; is the first thing executed if the alter statement included one.&lt;/li&gt;
&lt;li&gt;ATExecCmd &lt;a href="https://github.com/postgres/postgres/blob/master/src/backend/commands/tablecmds.c#L5323" rel="noopener noreferrer"&gt;executes&lt;/a&gt; the prepared command and ATExecDropConstraint &lt;a href="https://github.com/postgres/postgres/blob/master/src/backend/commands/tablecmds.c#L5490" rel="noopener noreferrer"&gt;drops the constraint&lt;/a&gt; that was prepared in ATPrepCmd &lt;a href="https://github.com/postgres/postgres/blob/master/src/backend/commands/tablecmds.c#L5102" rel="noopener noreferrer"&gt;during phase 1&lt;/a&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Now it's obvious the alter statement should be split and executed in this order:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;code&gt;ALTER TABLE users ALTER COLUMN email SET NOT NULL;&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;ALTER TABLE users DROP CONSTRAINT IF EXISTS email_not_null_chk;&lt;/code&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If PostgreSQL logging level is set to debug1, there will be an entry to confirm the optimization actually occurred:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;existing constraints on column "email" are sufficient to prove that it does not contain nulls&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Most importantly: TEST EVERYTHING!
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4xf0hia0q8h225zgglmw.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4xf0hia0q8h225zgglmw.jpg" alt="Untitled" width="500" height="680"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  References
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://www.postgresql.org/docs/current/sql-altertable.html#:~:text=table%20scan,is%20skipped." rel="noopener noreferrer"&gt;optimization&lt;/a&gt;&lt;br&gt;
&lt;a href="https://www.postgresql.org/docs/current/sql-altertable.html#:~:text=An%20ACCESS%20EXCLUSIVE,one%20required%20by%20any%20subcommand." rel="noopener noreferrer"&gt;set not null lock&lt;/a&gt;&lt;br&gt;
&lt;a href="https://www.postgresql.org/docs/current/sql-altertable.html#:~:text=THIS%20command%20acquires,%20a%20SHARE%20UPDATE%20EXCLUSIVE%20lock." rel="noopener noreferrer"&gt;validate constraint lock&lt;/a&gt;&lt;br&gt;
&lt;a href="https://www.postgresql.org/docs/current/explicit-locking.html#:~:text=Table%2013.2.%20,Conflicting%20Lock%20Modes" rel="noopener noreferrer"&gt;lock compatability&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;update (2025-08-18) PostgreSQL &lt;a href="https://www.postgresql.org/docs/current/sql-altertable.html#:~:text=and%20is%20not%20dropped%20in%20the%20same%20command" rel="noopener noreferrer"&gt;updated&lt;/a&gt; the official doc to clarify the optimization can only occur if the check constraint is not dropped in the same command. Kudos to the super responsive community.&lt;/p&gt;

</description>
      <category>tablescan</category>
      <category>optimization</category>
      <category>postgres</category>
      <category>postgressql</category>
    </item>
  </channel>
</rss>
